/**
 * 
 */
package com.seeyon.v3x.edoc.controller;

import static java.io.File.separator;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.joinwork.bpm.definition.BPMAbstractNode;
import net.joinwork.bpm.definition.BPMActivity;
import net.joinwork.bpm.definition.BPMProcess;
import net.joinwork.bpm.definition.BPMSeeyonPolicy;
import net.joinwork.bpm.definition.BPMTransition;
import net.joinwork.bpm.engine.wapi.WorkItem;
import net.joinwork.bpm.engine.wapi.WorkItemManager;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;
import org.springframework.web.servlet.ModelAndView;

import com.seeyon.cap.meetingsummary.domain.MtSummaryCAP;
import com.seeyon.cap.meetingsummary.manager.MtSummaryManagerCAP;
import com.seeyon.v3x.affair.constants.StateEnum;
import com.seeyon.v3x.affair.constants.SubStateEnum;
import com.seeyon.v3x.affair.domain.Affair;
import com.seeyon.v3x.affair.manager.AffairManager;
import com.seeyon.v3x.bulletin.domain.BulData;
import com.seeyon.v3x.bulletin.domain.BulType;
import com.seeyon.v3x.bulletin.manager.BaseBulletinManager;
import com.seeyon.v3x.bulletin.manager.BulDataManager;
import com.seeyon.v3x.bulletin.manager.BulTypeManager;
import com.seeyon.v3x.collaboration.Constant;
import com.seeyon.v3x.collaboration.domain.ColSuperviseDetail;
import com.seeyon.v3x.collaboration.domain.ColSupervisor;
import com.seeyon.v3x.collaboration.domain.ColTrackMember;
import com.seeyon.v3x.collaboration.domain.FlowData;
import com.seeyon.v3x.collaboration.domain.Party;
import com.seeyon.v3x.collaboration.domain.SuperviseTemplateRole;
import com.seeyon.v3x.collaboration.event.CollaborationCancelEvent;
import com.seeyon.v3x.collaboration.exception.ColException;
import com.seeyon.v3x.collaboration.manager.ColManager;
import com.seeyon.v3x.collaboration.manager.ColSuperviseManager;
import com.seeyon.v3x.collaboration.manager.impl.ColHelper;
import com.seeyon.v3x.collaboration.manager.impl.ColLock;
import com.seeyon.v3x.collaboration.templete.domain.ColBranch;
import com.seeyon.v3x.collaboration.templete.domain.Templete;
import com.seeyon.v3x.collaboration.templete.manager.TempleteManager;
import com.seeyon.v3x.collaboration.webmodel.ProcessModeSelectorModel;
import com.seeyon.v3x.common.SystemEnvironment;
import com.seeyon.v3x.common.appLog.AppLogAction;
import com.seeyon.v3x.common.appLog.manager.AppLogManager;
import com.seeyon.v3x.common.authenticate.domain.AgentModel;
import com.seeyon.v3x.common.authenticate.domain.MemberAgentBean;
import com.seeyon.v3x.common.authenticate.domain.User;
import com.seeyon.v3x.common.constants.ApplicationCategoryEnum;
import com.seeyon.v3x.common.constants.Constants;
import com.seeyon.v3x.common.dao.paginate.Pagination;
import com.seeyon.v3x.common.encrypt.CoderFactory;
import com.seeyon.v3x.common.exceptions.BusinessException;
import com.seeyon.v3x.common.exceptions.MessageException;
import com.seeyon.v3x.common.filemanager.Attachment;
import com.seeyon.v3x.common.filemanager.V3XFile;
import com.seeyon.v3x.common.filemanager.manager.AttachmentEditHelper;
import com.seeyon.v3x.common.filemanager.manager.AttachmentManager;
import com.seeyon.v3x.common.filemanager.manager.FileManager;
import com.seeyon.v3x.common.filemanager.manager.Util;
import com.seeyon.v3x.common.flag.BrowserFlag;
import com.seeyon.v3x.common.flag.SysFlag;
import com.seeyon.v3x.common.i18n.LocaleContext;
import com.seeyon.v3x.common.i18n.ResourceBundleUtil;
import com.seeyon.v3x.common.metadata.Metadata;
import com.seeyon.v3x.common.metadata.MetadataItem;
import com.seeyon.v3x.common.metadata.MetadataNameEnum;
import com.seeyon.v3x.common.metadata.manager.MetadataManager;
import com.seeyon.v3x.common.office.HandWriteManager;
import com.seeyon.v3x.common.office.HtmlHandWriteManager;
import com.seeyon.v3x.common.permission.manager.PermissionManager;
import com.seeyon.v3x.common.processlog.ProcessLogAction;
import com.seeyon.v3x.common.processlog.domain.ProcessLog;
import com.seeyon.v3x.common.processlog.manager.ProcessLogManager;
import com.seeyon.v3x.common.security.SecurityCheck;
import com.seeyon.v3x.common.security.roleauthcheck.CheckRoleAccess;
import com.seeyon.v3x.common.security.roleauthcheck.RoleType;
import com.seeyon.v3x.common.taglibs.functions.Functions;
import com.seeyon.v3x.common.usermessage.MessageContent;
import com.seeyon.v3x.common.usermessage.MessageReceiver;
import com.seeyon.v3x.common.usermessage.UserMessageManager;
import com.seeyon.v3x.common.utils.UUIDLong;
import com.seeyon.v3x.common.web.BaseController;
import com.seeyon.v3x.common.web.login.CurrentUser;
import com.seeyon.v3x.common.web.util.ApplicationContextHolder;
import com.seeyon.v3x.common.web.util.WebUtil;
import com.seeyon.v3x.common.web.workflow.DateSharedWithWorkflowEngineThreadLocal;
import com.seeyon.v3x.config.domain.ConfigItem;
import com.seeyon.v3x.config.manager.ConfigManager;
import com.seeyon.v3x.doc.domain.DocResource;
import com.seeyon.v3x.doc.manager.DocHierarchyManager;
import com.seeyon.v3x.edoc.EdocEnum;
import com.seeyon.v3x.edoc.EdocEnum.MarkCategory;
import com.seeyon.v3x.edoc.EdocEnum.edocType;
import com.seeyon.v3x.edoc.constants.EdocConstant;
import com.seeyon.v3x.edoc.constants.EdocCustomConstant;
import com.seeyon.v3x.edoc.constants.EdocCustomerTypeEnum;
import com.seeyon.v3x.edoc.constants.EdocNavigationEnum;
import com.seeyon.v3x.edoc.constants.EdocNavigationEnum.RegisterRetreatState;
import com.seeyon.v3x.edoc.constants.EdocNavigationEnum.RegisterState;
import com.seeyon.v3x.edoc.constants.EdocQueryColConstants;
import com.seeyon.v3x.edoc.constants.PackageColValueInter;
import com.seeyon.v3x.edoc.constants.QueryCol;
import com.seeyon.v3x.edoc.constants.QueryColTemplate;
import com.seeyon.v3x.edoc.domain.EdocArchiveModifyLog;
import com.seeyon.v3x.edoc.domain.EdocBody;
import com.seeyon.v3x.edoc.domain.EdocCategory;
import com.seeyon.v3x.edoc.domain.EdocCustomerType;
import com.seeyon.v3x.edoc.domain.EdocForm;
import com.seeyon.v3x.edoc.domain.EdocFormExtendInfo;
import com.seeyon.v3x.edoc.domain.EdocMark;
import com.seeyon.v3x.edoc.domain.EdocMarkDefinition;
import com.seeyon.v3x.edoc.domain.EdocOpinion;
import com.seeyon.v3x.edoc.domain.EdocRegister;
import com.seeyon.v3x.edoc.domain.EdocSummary;
import com.seeyon.v3x.edoc.domain.EdocSummaryRelation;
import com.seeyon.v3x.edoc.domain.EdocZcdb;
import com.seeyon.v3x.edoc.domain.RegisterBody;
import com.seeyon.v3x.edoc.exception.EdocException;
import com.seeyon.v3x.edoc.exception.EdocMarkHistoryExistException;
import com.seeyon.v3x.edoc.manager.EdocArchiveModifyLogManager;
import com.seeyon.v3x.edoc.manager.EdocCategoryManager;
import com.seeyon.v3x.edoc.manager.EdocCustomerTypeManager;
import com.seeyon.v3x.edoc.manager.EdocFormManager;
import com.seeyon.v3x.edoc.manager.EdocHelper;
import com.seeyon.v3x.edoc.manager.EdocInnerMarkDefinitionManager;
import com.seeyon.v3x.edoc.manager.EdocManager;
import com.seeyon.v3x.edoc.manager.EdocMarkDefinitionManager;
import com.seeyon.v3x.edoc.manager.EdocMarkHistoryManager;
import com.seeyon.v3x.edoc.manager.EdocMarkManager;
import com.seeyon.v3x.edoc.manager.EdocPermissionControlManager;
import com.seeyon.v3x.edoc.manager.EdocRegisterManager;
import com.seeyon.v3x.edoc.manager.EdocRoleHelper;
import com.seeyon.v3x.edoc.manager.EdocSummaryManager;
import com.seeyon.v3x.edoc.manager.EdocSummaryRelationManager;
import com.seeyon.v3x.edoc.manager.EdocSuperviseManager;
import com.seeyon.v3x.edoc.manager.EdocSwitchHelper;
import com.seeyon.v3x.edoc.manager.EdocZcdbManager;
import com.seeyon.v3x.edoc.manager.RegisterBodyManager;
import com.seeyon.v3x.edoc.util.DataUtil;
import com.seeyon.v3x.edoc.util.EdocOpinionDisplayUtil;
import com.seeyon.v3x.edoc.util.EdocUtil;
import com.seeyon.v3x.edoc.webmodel.EdocFormModel;
import com.seeyon.v3x.edoc.webmodel.EdocMarkModel;
import com.seeyon.v3x.edoc.webmodel.EdocOpinionDisplayConfig;
import com.seeyon.v3x.edoc.webmodel.EdocOpinionModel;
import com.seeyon.v3x.edoc.webmodel.EdocSearchModel;
import com.seeyon.v3x.edoc.webmodel.EdocSummaryModel;
import com.seeyon.v3x.edoc.webmodel.MoreSignSelectPerson;
import com.seeyon.v3x.event.EventDispatcher;
import com.seeyon.v3x.excel.DataRecord;
import com.seeyon.v3x.excel.FileToExcelManager;
import com.seeyon.v3x.exchange.domain.EdocRecieveRecord;
import com.seeyon.v3x.exchange.manager.RecieveEdocManager;
import com.seeyon.v3x.flowperm.domain.FlowPerm;
import com.seeyon.v3x.flowperm.manager.FlowPermManager;
import com.seeyon.v3x.index.share.interfaces.IndexEnable;
import com.seeyon.v3x.index.share.interfaces.IndexManager;
import com.seeyon.v3x.indexInterface.IndexInitConfig;
import com.seeyon.v3x.indexInterface.IndexManager.UpdateIndexManager;
import com.seeyon.v3x.news.manager.NewsDataManager;
import com.seeyon.v3x.news.manager.NewsTypeManager;
import com.seeyon.v3x.organization.OrganizationHelper;
import com.seeyon.v3x.organization.domain.V3xOrgAccount;
import com.seeyon.v3x.organization.domain.V3xOrgDepartment;
import com.seeyon.v3x.organization.domain.V3xOrgEntity;
import com.seeyon.v3x.organization.domain.V3xOrgLevel;
import com.seeyon.v3x.organization.domain.V3xOrgMember;
import com.seeyon.v3x.organization.domain.V3xOrgPost;
import com.seeyon.v3x.organization.domain.V3xOrgRole;
import com.seeyon.v3x.organization.domain.V3xOrgTeam;
import com.seeyon.v3x.organization.domain.secondarypost.ConcurrentPost;
import com.seeyon.v3x.organization.domain.secondarypost.MemberPost;
import com.seeyon.v3x.organization.manager.OrgManager;
import com.seeyon.v3x.system.signet.manager.SignetManager;
import com.seeyon.v3x.util.Datetimes;
import com.seeyon.v3x.util.PopSelectParseUtil;
import com.seeyon.v3x.util.Strings;
import com.seeyon.v3x.util.XMLCoder;
import com.seeyon.v3x.workflow.event.WorkflowEventListener;
import com.seeyon.v3x.workflow.event.WorkflowEventListener.NodeAddition;
 
/**
 * 类描述：
 * 创建日期：
 *
 * @author liaoj
 * @version 1.0   
 * @since JDK 5.0
 */
public class EdocController extends BaseController{
	
	
	private static final Log log = LogFactory.getLog(EdocController.class);
	 
	private static final String SHANG_KA = "shangka";
	//上卡操作时原始文单的id
	private static final String BEFORE_SHANGKA_FORMID = "beforeShangKaFormId"; 
	
	private MetadataManager metadataManager;
	private OrgManager orgManager;
	private AttachmentManager attachmentManager;
	private EdocManager edocManager;
	private UpdateIndexManager updateIndexManager;
	private AffairManager affairManager;
	private EdocPermissionControlManager edocPermissionControlManager;
	private EdocFormManager edocFormManager;
	private TempleteManager templeteManager;
	private FlowPermManager flowPermManager;
	private PermissionManager permissionManager;
	private RecieveEdocManager recieveEdocManager;
	private EdocMarkManager edocMarkManager;
	private EdocMarkHistoryManager edocMarkHistoryManager;
	private EdocInnerMarkDefinitionManager edocInnerMarkDefinitionManager;
	private EdocMarkDefinitionManager edocMarkDefinitionManager;
	private EdocSummaryManager edocSummaryManager;
	private EdocSuperviseManager edocSuperviseManager;
	private ColSuperviseManager colSuperviseManager;
	
	private HandWriteManager handWriteManager;
	private HtmlHandWriteManager htmlHandWriteManager;
	private NewsTypeManager newsTypeManager;  
	private BulTypeManager bulTypeManager;
    private BulDataManager bulDataManager;
    private NewsDataManager newsDataManager;
    private UserMessageManager userMessageManager;
    private ProcessLogManager processLogManager ;
    private FileManager fileManager;
    private DocHierarchyManager docHierarchyManager;
	private FileToExcelManager fileToExcelManager;
    private IndexManager indexManager;
    private ColManager colManager;
    private EdocZcdbManager edocZcdbManager;
    private EdocArchiveModifyLogManager edocArchiveModifyLogManager;
    private EdocCategoryManager edocCategoryManager;
    private MtSummaryManagerCAP mtSummaryManagerCAP;
    private AppLogManager appLogManager;
    private boolean flag=false;
    
    private ConfigManager configManager;
    
	private EdocSummaryRelationManager edocSummaryRelationManager;

	public void setEdocSummaryRelationManager(
			EdocSummaryRelationManager edocSummaryRelationManager) {
		this.edocSummaryRelationManager = edocSummaryRelationManager;
	}
	
	public void setMtSummaryManagerCAP(MtSummaryManagerCAP mtSummaryManagerCAP) {
		this.mtSummaryManagerCAP = mtSummaryManagerCAP;
	}
	
	public void setEdocCategoryManager(EdocCategoryManager edocCategoryManager) {
		this.edocCategoryManager = edocCategoryManager;
	}
    public void setEdocArchiveModifyLogManager(
			EdocArchiveModifyLogManager edocArchiveModifyLogManager) {
		this.edocArchiveModifyLogManager = edocArchiveModifyLogManager;
	}
   
	private EdocRegisterManager edocRegisterManager;
	public EdocRegisterManager getEdocRegisterManager() {
		return edocRegisterManager;
	}
	private RegisterBodyManager registerBodyManager;
    public void setRegisterBodyManager(RegisterBodyManager registerBodyManager) {
		this.registerBodyManager = registerBodyManager;
	}
    /**
     * cy add
     */
    private EdocCustomerTypeManager edocCustomerTypeManager;
    public void setEdocRegisterManager(EdocRegisterManager edocRegisterManager) {
		this.edocRegisterManager = edocRegisterManager;
	}
	public void setEdocCustomerTypeManager(EdocCustomerTypeManager edocCustomerTypeManager) {
		this.edocCustomerTypeManager = edocCustomerTypeManager;
	}
    
	public void setEdocZcdbManager(EdocZcdbManager edocZcdbManager) {
		this.edocZcdbManager = edocZcdbManager;
	}
    
	public void setColManager(ColManager colManager) {
		this.colManager = colManager;
	}
	public IndexManager getIndexManager() {
		return indexManager;
	}
	public void setHandWriteManager(HandWriteManager handWriteManager) {
		this.handWriteManager = handWriteManager;
	}
	public void setIndexManager(IndexManager indexManager) {
		this.indexManager = indexManager;
	}

	public UserMessageManager getUserMessageManager() {
		return userMessageManager;
	}

	public void setUserMessageManager(UserMessageManager userMessageManager) {
		this.userMessageManager = userMessageManager;
	}

	public void setHtmlHandWriteManager(HtmlHandWriteManager htmlHandWriteManager)
	{
		this.htmlHandWriteManager=htmlHandWriteManager;
	}
	
	public HtmlHandWriteManager getHtmlHandWriteManager()
	{
		return this.htmlHandWriteManager;
	}
	
	public RecieveEdocManager getRecieveEdocManager() {
		return recieveEdocManager;
	}

	public EdocMarkManager getEdocMarkManager() {
		return edocMarkManager;
	}

	public void setEdocMarkManager(EdocMarkManager edocMarkManager) {
		this.edocMarkManager = edocMarkManager;
	}

	public void setRecieveEdocManager(RecieveEdocManager recieveEdocManager) {
		this.recieveEdocManager = recieveEdocManager;
	}

    public void setPermissionManager(PermissionManager permissionManager) {
		this.permissionManager = permissionManager;
	}
	
	public void setFlowPermManager(FlowPermManager flowPermManager)
	{
		this.flowPermManager=flowPermManager;
	}
	
	public void setTempleteManager(TempleteManager templeteManager) {
        this.templeteManager = templeteManager;
    }
	
	public void setEdocFormManager(EdocFormManager edocFormManager)
	{
		this.edocFormManager=edocFormManager;
	}
	
	public void setAffairManager(AffairManager affairManager) {
        this.affairManager = affairManager;
    }
	
	public UpdateIndexManager getUpdateIndexManager() {
		return updateIndexManager;
	}
	

	public void setAppLogManager(AppLogManager appLogManager) {
		this.appLogManager = appLogManager;
	}

	public void setUpdateIndexManager(UpdateIndexManager updateIndexManager) {
		this.updateIndexManager = updateIndexManager;
	}
	
	public void setEdocManager(EdocManager edocManager)
	{
		this.edocManager=edocManager;
	}
	
	public void setAttachmentManager(AttachmentManager attachmentManager) {
        this.attachmentManager = attachmentManager;
    }
	
    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }
	
    public void setMetadataManager(MetadataManager metadataManager) {
        this.metadataManager = metadataManager;
    }
    public void setEdocPermissionControlManager(
            EdocPermissionControlManager edocPermissionControlManager) {
        this.edocPermissionControlManager = edocPermissionControlManager;
    }
    


	public ConfigManager getConfigManager() {
		return configManager;
	}

	public void setConfigManager(ConfigManager configManager) {
		this.configManager = configManager;
	}

	@Override
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return null;
	}
	
	public ModelAndView entryManager(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = new ModelAndView("edoc/edocFrameEntry");
		modelAndView.addObject("entry", request.getParameter("entry"));
		String toFrom = request.getParameter("toFrom");
		if(Strings.isNotBlank(toFrom) && ("newEdoc").equals(toFrom) && Strings.isNotBlank(request.getParameter("templeteId"))) {
			int edocType = Strings.isBlank(request.getParameter("edocType"))?0:Integer.parseInt(request.getParameter("edocType"));
			//检查是否有公文发起权
			int roleEdocType = edocType==1?3:edocType;
	        boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(CurrentUser.get().getLoginAccount(), CurrentUser.get().getId(), roleEdocType);
	        if(isEdocCreateRole==false && !"agent".equals(request.getParameter("app"))) {//没有公文发起权不能发送
	        	modelAndView = new ModelAndView("common/redirect");
	        	String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_not_edoccreate");
	        	modelAndView.addObject("redirectURL", BaseController.REDIRECT_BACK);
	        	modelAndView.addObject("errMsg", errMsg);
	        	return modelAndView;
	        }  
		}
    	return modelAndView ;
	}
	public ModelAndView fullEditor(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = new ModelAndView("edoc/fullEditor");
		return modelAndView;
		
	}
	public ModelAndView newLeave(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = new ModelAndView("edoc/newLeave");
		return modelAndView;
		
	}
	/**
	 * 收文管理
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView recManager(HttpServletRequest request, HttpServletResponse response) throws Exception {		
		String toFrom = request.getParameter("toFrom"); 
		String exchangeId = request.getParameter("exchangeId");
		String id = request.getParameter("id");
		String registerId = request.getParameter("registerId");
		String edocId = request.getParameter("edocId");
		String affairId = Strings.isBlank(request.getParameter("affairId"))?"":request.getParameter("affairId");
		String track = Strings.isBlank(request.getParameter("track"))?"":request.getParameter("track");
		String templeteId = request.getParameter("templeteId");
		String from = Strings.isBlank(request.getParameter("from"))?"listPending":request.getParameter("from");
		//branches_a8_v350_r_gov GOV-2641  唐桂林修改政务收文阅件链接 start
		if(Strings.isNotBlank(request.getParameter("objectId"))) {
			EdocSummary summary = edocSummaryManager.findById(Long.parseLong(request.getParameter("objectId")));
			if(summary != null && summary.getProcessType()==2) {//阅文
				toFrom = "listReading";
			}
		}
		//branches_a8_v350_r_gov GOV-2641  唐桂林修改政务收文阅件链接 end
		StringBuffer url = new StringBuffer();
		url.append("/edocController.do?method=listIndex&edocType="+EdocEnum.edocType.recEdoc.ordinal());
		if(Strings.isNotBlank(toFrom)) {
			from = toFrom;
			url.append("&toFrom="+toFrom);
		}
		if(Strings.isNotBlank(track)) {
			url.append("&track="+track);
		}
		if(Strings.isNotBlank(registerId)) {
			url.append("&registerId="+registerId);
		}
		if(Strings.isNotBlank(id)) {
			if(Strings.isBlank(registerId)) {
				url.append("&registerId="+id);
			} else {
				url.append("&id="+id);
			}
		}
		if(Strings.isNotBlank(exchangeId)) {
			url.append("&exchangeId="+exchangeId);
		}
		if(Strings.isNotBlank(edocId)) {
			url.append("&edocId="+edocId);
		}
		if(Strings.isNotBlank(templeteId)) {
			url.append("&templeteId="+templeteId);
		}
		if(Strings.isNotBlank(affairId)) {
			url.append("&affairId="+affairId);
		}
		if(Strings.isNotBlank(request.getParameter("listType"))) {
			url.append("&listType="+request.getParameter("listType"));
		}	
		if(Strings.isNotBlank(request.getParameter("app"))) {
			url.append("&app="+request.getParameter("app"));
		}
		String comm = Strings.isBlank(request.getParameter("comm"))?"":request.getParameter("comm");
		if("newEdoc".equals(toFrom)) {//表示收文分发
			comm = "distribute";
		}
		url.append("&comm="+comm);
		url.append("&from="+from);
		return super.redirectModelAndView(url.toString());
	}
	/**
	 * 发文管理
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView sendManager(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String affairId = Strings.isBlank(request.getParameter("affairId"))?"":request.getParameter("affairId");
		String track = Strings.isBlank(request.getParameter("track"))?"":request.getParameter("track");
		String templeteId = Strings.isNotBlank(request.getParameter("templeteId"))?request.getParameter("templeteId"):"";
		String toFrom = request.getParameter("toFrom");
		String from = Strings.isBlank(request.getParameter("from"))?"listPending":request.getParameter("from");
		String meetingSummaryId = request.getParameter("meetingSummaryId");
		String comm = request.getParameter("comm");
		String edocId = request.getParameter("edocId");
		String transmitSendNewEdocId = request.getParameter("transmitSendNewEdocId");
		if(Strings.isNotBlank(toFrom)) {
			from = toFrom;
		}
		return super.redirectModelAndView("/edocController.do?method=listIndex&comm="+comm+"&from="+from+"&toFrom="+toFrom+"&track="+track+"&controller=edocController.do&edocType="+EdocEnum.edocType.sendEdoc.ordinal()
				+"&templeteId="+templeteId+"&affairId="+affairId+(Strings.isNotBlank(meetingSummaryId)?"&meetingSummaryId="+meetingSummaryId:"")
				+"&edocId="+edocId+"&transmitSendNewEdocId="+transmitSendNewEdocId);
	}
	/**
	 * 签报管理
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView signReport(HttpServletRequest request,
			HttpServletResponse response) throws Exception {	
		String affairId = Strings.isBlank(request.getParameter("affairId"))?"":request.getParameter("affairId");
		String track = Strings.isBlank(request.getParameter("track"))?"":request.getParameter("track");
		String toFrom = request.getParameter("toFrom");
		String templeteId = request.getParameter("templeteId");
		String from = Strings.isBlank(request.getParameter("from"))?"listPending":request.getParameter("from");
		if(Strings.isNotBlank(toFrom)) {
			from = toFrom;
		}
		return super.redirectModelAndView("/edocController.do?method=listIndex&from="+from+"&toFrom="+toFrom+"&track="+track+"&controller=edocController.do&edocType="+EdocEnum.edocType.signReport.ordinal()+"&templeteId="+templeteId+"&affairId="+affairId);
	}
    /**
     * 新建公文
     * @param request
     * @param response   
     * @return
     * @throws Exception
     */
	
    public ModelAndView newEdoc(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //会议纪要转公文 获得会议纪要ID 
        String meetingSummaryId = request.getParameter("meetingSummaryId");
    	User user = CurrentUser.get();
    	long subType = Strings.isBlank(request.getParameter("subType"))?-1:Long.parseLong(request.getParameter("subType"));
    	EdocCategory edocCategory = null;
        ModelAndView modelAndView = new ModelAndView("edoc/newEdoc");
        String edocType=request.getParameter("edocType");
        modelAndView.addObject("pageview", request.getParameter("pageview"));// 已阅、待阅列表中阅转办页面跳转标识 wangjingjing
        modelAndView.addObject("source", request.getParameter("source"));
        int iEdocType=-1;
        if(edocType!=null && !"".equals(edocType))
        {
        	iEdocType=Integer.parseInt(edocType);
        }
        EdocRegister edocRegister = null;
        RegisterBody registerBody = null;
        boolean canUpdateContent=true;//是否允许修改正文       
    	String checkOption="";//判断撰文类型
    	String content="";
        String comm=request.getParameter("comm");
        String from = request.getParameter("from");
        String s_summaryId = request.getParameter("summaryId");//表单ID
        String templeteId = request.getParameter("templeteId");//表单模板ID
        String oldtempleteId=request.getParameter("oldtempleteId");//原始模板ID
        BPMProcess process = null;        
        boolean isSystem = true;
        List<Attachment> atts = null;
        boolean canDeleteOriginalAtts = true;
        boolean cloneOriginalAtts = false;
        EdocOpinion senderOpinion = null;
        EdocSummary summary=null;
        EdocForm defaultEdocForm=null;
        Long edocFormId=0L;
        String templeteType=""; 
        String register=request.getParameter("register"); 
        //openTempleteOfExchangeRegist:公文交换调用模板分发
        final boolean openTempleteOfExchangeRegist = "distribute".equals(register);
        EdocRecieveRecord record =null;
        //基准时长，在调用模板的时候对其赋值（直接调用模板|来自待发的模板）
        Integer standarduration = 0;
        long registerId = Strings.isBlank(request.getParameter("registerId"))?-1:Long.parseLong(request.getParameter("registerId"));
        //为了兼容老数据参数，将登记转到分发，如链接
        if("register".equals(comm)) {
        	comm = "distribute";
        }
        boolean isFromWaitSend = false;
        //对已有流程的协同（重复发起、转发、保存待发），在页面上存储其定义XML
        if("transmitSend".equals(comm))
        {
        	String strEdocId=request.getParameter("edocId");
        	String transmitSendNewEdocId=request.getParameter("transmitSendNewEdocId");
        	Long edocId=0L;
        	if(strEdocId!=null && !"".equals(strEdocId)){edocId=Long.parseLong(strEdocId);}
        	summary=edocManager.getEdocSummaryById(edocId,true);        	
        	atts = attachmentManager.getByReference(summary.getId(), summary.getId());
        	canDeleteOriginalAtts=false;
        	cloneOriginalAtts=true;        	
            defaultEdocForm=edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType); 
            EdocBody body=summary.getFirstBody(); 
            Date createDate = body.getCreateTime();
            FileManager fileManager = (FileManager)ApplicationContextHolder.getBean("fileManager");
    		if(Constants.EDITOR_TYPE_OFFICE_EXCEL.equals(body.getContentType())
    				||Constants.EDITOR_TYPE_OFFICE_WORD.equals(body.getContentType())
    				||Constants.EDITOR_TYPE_WPS_WORD.equals(body.getContentType())
    				||Constants.EDITOR_TYPE_WPS_EXCEL.equals(body.getContentType())){//非html正文都以附件形势转发
    			InputStream in = null;
    			try { 
    				//查找清除了痕迹的公文。
    				Long srcFileId=Long.parseLong(body.getContent());
    				if(transmitSendNewEdocId!=null&&!"".equals(transmitSendNewEdocId))
    					srcFileId=Long.parseLong(transmitSendNewEdocId);
    				String srcPath=fileManager.getFolder(createDate, true) + separator+ String.valueOf(srcFileId);
    				//1.解密文件
    				String newPath=CoderFactory.getInstance().decryptFileToTemp(srcPath);
    				//2.转换成标准正文
    				String newPathName = SystemEnvironment.getSystemTempFolder() + separator + String.valueOf(UUIDLong.longUUID());
    				Util.jinge2StandardOffice(newPath, newPathName);
    				//3.构造输入流
    				in = new FileInputStream(new File(newPathName)) ;
    				V3XFile f = fileManager.save(in, ApplicationCategoryEnum.edoc, summary.getSubject() + EdocUtil.getOfficeFileExt(body.getContentType()), createDate, false);
    				atts.add(new Attachment(f, ApplicationCategoryEnum.edoc, com.seeyon.v3x.common.filemanager.Constants.ATTACHMENT_TYPE.FILE));
    			}catch (Exception e) {
    				log.error("收文转发文错误 ", e);
    			}finally{
    				IOUtils.closeQuietly(in);
    			}
    		}else if(Constants.EDITOR_TYPE_PDF.equals(body.getContentType())){
    			String srcPath=fileManager.getFolder(createDate, true) + separator+ String.valueOf(body.getContent());
    			InputStream in = new FileInputStream(new File(srcPath)) ;
				V3XFile f = fileManager.save(in, ApplicationCategoryEnum.edoc, summary.getSubject() + ".pdf", createDate, false);
				atts.add(new Attachment(f, ApplicationCategoryEnum.edoc, com.seeyon.v3x.common.filemanager.Constants.ATTACHMENT_TYPE.FILE));
    		}else
    		{//html正文，先生成文件    			
    			V3XFile f =fileManager.save(body.getContent()==null?"":body.getContent(), ApplicationCategoryEnum.edoc, summary.getSubject()+".htm", createDate, false);    			
				atts.add(new Attachment(f, ApplicationCategoryEnum.edoc, com.seeyon.v3x.common.filemanager.Constants.ATTACHMENT_TYPE.FILE));
    		}
    		summary =new EdocSummary();
            summary.setCreatePerson(user.getName());
            body = new EdocBody();
            String bodyContentType=Constants.EDITOR_TYPE_OFFICE_WORD;
            if(com.seeyon.v3x.common.SystemEnvironment.hasPlugin("officeOcx")==false){bodyContentType=Constants.EDITOR_TYPE_HTML;}
            body.setContentType(bodyContentType);
            summary.getEdocBodies().add(body); 
            summary.setOrgAccountId(user.getLoginAccount());
            summary.setEdocType(EdocEnum.edocType.sendEdoc.ordinal());
            //转发时候，放入session，调用模版时候备用
            request.getSession().setAttribute("transmitSendAtts",atts);
        }else if("register".equals(comm))
        {
        	String strEdocId=request.getParameter("edocId");
        	String exchangeType=request.getParameter("exchangeType");
        	String exchangeOrgId=request.getParameter("exchangeOrgId");
        	String exchangeId=request.getParameter("exchangeId");
        	Long  _exchangeOrgId=0L;
        	if(Strings.isNotBlank(exchangeOrgId) && Strings.isNotBlank(exchangeType)){
        		_exchangeOrgId=getAccountIdOfRegisterByOrgIdAndOrgType(Long.parseLong(exchangeOrgId),Integer.parseInt(exchangeType));
        	}else{//首页过来的数据没有exchangeType和exchangeOrgId
        		_exchangeOrgId=getAccountIdOfRegisterByExchangeId(Long.parseLong(exchangeId));
        	}
			// 登记公文，判断当前操作人是否可以登记此公文
			record = recieveEdocManager.getEdocRecieveRecord(Long.parseLong(exchangeId));
			if (record.getRegisterUserId() != user.getId()) {
				Long agentId = MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(),record.getRegisterUserId() );
				if(agentId != null) {
					if(!Long.valueOf(user.getId()).equals(agentId)){
						// 公文登记人已经转换
						String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasChanged_register");
						if (Strings.isNotBlank(exchangeOrgId) && Strings.isNotBlank(exchangeType)) {
							// 转到待登记
							PrintWriter out = response.getWriter();
							// super.printV3XJS(out);
							out.println("<script>");
							out.println("alert(\"" + errMsg + "\")");
							out.println("if(window.dialogArguments){"); // 弹出
							out.println("  window.returnValue = \"true\";");
							out.println("  window.close();");
							out.println("}else{");
							out.println("	parent.location.href='edocController.do?method=edocFrame&from=listRegisterPending&edocType=1'");
							out.println("}");
							out.println("");
							out.println("</script>");
							return null;
						} else {
							// 首页过来的数据没有exchangeType和exchangeOrgId,刷新父页面
							PrintWriter out = response.getWriter();
							// super.printV3XJS(out);
							out.println("<script>");
							out.println("alert('" + errMsg + "');");
							out.println("if(window.dialogArguments){"); // 弹出
							out.println("window.returnValue='true';window.close();}else{");
							out.println("parent.parent.location.reload(true)");
							out.println("}");
							// out.println("history.go(-1);");
							out.println("</script>");
							return null;
						}
					}
				}
			}
			// 公文已经被从待登记中回退，所以也不能继续登记
			if (record.getStatus() == com.seeyon.v3x.exchange.util.Constants.C_iStatus_Torecieve) {
				// 转到待登记
				String errMsg = ResourceBundleUtil.getString(
						"com.seeyon.v3x.edoc.resources.i18n.EdocResource",
						"alert_hasBeStepBack_already");
				PrintWriter out = response.getWriter();
				//super.printV3XJS(out);
				out.println("<script>");
				out.println("alert(\"" + errMsg + "\")");
				out.println("if(window.dialogArguments){"); // 弹出
				out.println("  window.returnValue = \"true\";");
				out.println("  window.close();");
				out.println("}else{");
				out.println("parent.location.href='edocController.do?method=edocFrame&from=listRegisterPending&edocType=1'");
				out.println("}");
				out.println("");
				out.println("</script>");
				return null;
			}
        	Long edocId=0L;
        	if(strEdocId!=null && !"".equals(strEdocId)){edocId=Long.parseLong(strEdocId);}
        	summary=edocManager.getEdocSummaryById(edocId,true);        	
        	atts = excludeType2ToNewAttachmentList(summary);
        	String createPersionName = user.getName();
        	if (record.getRegisterUserId() != user.getId()) {
        		V3xOrgMember member = orgManager.getMemberById(record.getRegisterUserId());
        		createPersionName = member.getName();
        	}
        	summary = cloneNewSummaryAndSetProperties(createPersionName, summary, _exchangeOrgId,record.getContentNo());
        	summary.setEdocType(EdocEnum.edocType.recEdoc.ordinal());
        	canDeleteOriginalAtts=false;
        	cloneOriginalAtts=true;
            defaultEdocForm=edocFormManager.getDefaultEdocForm(summary.getOrgAccountId(),iEdocType); 
        	modelAndView.addObject("strEdocId", strEdocId);
        }
        else if (StringUtils.isNotEmpty(templeteId)) {//调用模板
			Long id = new Long(templeteId);
			//检查是否有调用此模板的权限
	        boolean isTemplate=templeteManager.hasAccSystemTempletes(id, user.getId());
	        Templete templete = templeteManager.get(id);
	        isSystem = templete.getIsSystem();
	        if(isTemplate==false && isSystem==true)
	        {//没有公文发起权不能发送
	        	String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","alert_not_edoctempleteload");
	        	request.setAttribute("errMsg",errMsg);
	        	request.setAttribute("errMsgAlert", true);
	        	return super.redirectModelAndView(BaseController.REDIRECT_BACK);
	        }
	        standarduration = templete.getStandardDuration();
			
			//yangzd 如果新建公文时，先调用流程模板，再调用格式模板，则会本次要保持流程模板；反之也是。
			
			Templete oldtemplete=null; 
			Long oldid=null;
			//yangzd
			if (StringUtils.isNotEmpty(oldtempleteId)&&!oldtempleteId.equals("1"))
			{
				oldid = new Long(oldtempleteId);
				oldtemplete = templeteManager.get(oldid);
			}
			modelAndView.addObject("isFromTemplate", templete.getIsSystem() || templete.getFormParentId() != null);
            modelAndView.addObject("templateType",templete.getType());
            templeteType=templete.getType();
            
            if(iEdocType==-1)
            {
            	iEdocType=EdocUtil.getEdocTypeByTemplateType(templete.getCategoryType());
            	edocType=Integer.toString(iEdocType);
            }
            
            if(!Templete.Type.text.name().equals(templete.getType())){
				List<ColBranch> branchs = this.templeteManager.getBranchsByTemplateId(id,ApplicationCategoryEnum.edoc.ordinal());
	            modelAndView.addObject("branchs", EdocHelper.transformBranch(branchs, true));
	            if(branchs != null) {
	            	List<V3xOrgEntity> entities = this.orgManager.getUserDomain(user.getId(), V3xOrgEntity.VIRTUAL_ACCOUNT_ID, V3xOrgEntity.ORGENT_TYPE_TEAM);
	            	if(entities != null && !entities.isEmpty()){
	            		V3xOrgTeam team = null;
	            		List<V3xOrgTeam> teams = new ArrayList<V3xOrgTeam>();
	            		for(V3xOrgEntity entity:entities){
	            			team = (V3xOrgTeam)entity;
	            			if(team != null && team.getAllMembers() != null && team.getAllMembers().contains(user.getId())){
	            				teams.add(team);
	            			}
	            		}
	            		modelAndView.addObject("teams", teams);
	            	}
	            	
	            	V3xOrgMember mem = orgManager.getMemberById(user.getId());
	            	List<MemberPost> secondPosts = mem.getSecond_post();
	            	modelAndView.addObject("secondPosts", secondPosts);
	            }
	            process = BPMProcess.fromXML(templete.getWorkflow()); //重新生成，因为要取新的节点名称
            }
            //yangzd 读取上一次的非正文模板的流程
            else
            {
    				if(null!=oldtemplete&&!Templete.Type.text.name().equals(oldtemplete.getType()))
    				{

    					List<ColBranch> branchs = this.templeteManager.getBranchsByTemplateId(oldid,ApplicationCategoryEnum.edoc.ordinal());
    		            modelAndView.addObject("branchs", branchs);
    		            if(branchs != null) {
    		            	modelAndView.addObject("teams", this.orgManager.getUserDomain(user.getId(), user.getLoginAccount(), V3xOrgEntity.ORGENT_TYPE_TEAM));
    		            	V3xOrgMember mem = orgManager.getMemberById(user.getId());
    		            	List<MemberPost> secondPosts = mem.getSecond_post();
    		            	modelAndView.addObject("secondPosts", secondPosts);
    		            }
    		            
    		            process = BPMProcess.fromXML(oldtemplete.getWorkflow()); //重新生成，因为要取新的节点名称
    				}
    			
            }
            //yangzd
            iEdocType=EdocEnum.getEdocTypeByTemplateCategory(templete.getCategoryType());
            //通过交换进行登记，调用模板
            if(openTempleteOfExchangeRegist){
             	String strEdocId=request.getParameter("strEdocId");
             	String orgAccountIdStr=request.getParameter("orgAccountId");
             	Long edocId=0L;
             	Long orgAccountId=0L;
             	if(Strings.isNotBlank(strEdocId)){edocId=Long.parseLong(strEdocId);}
             	if(Strings.isNotBlank(orgAccountIdStr)){orgAccountId=Long.parseLong(orgAccountIdStr);}

             	//分发直接与登记关联，去掉与签收表之间的关联
            	edocRegister = edocRegisterManager.findRegisterById(registerId);
            	if(edocRegister != null) {
            		registerId = edocRegister.getId();
                	registerBody = edocRegisterManager.findRegisterBodyByRegisterId(edocRegister.getId());
                	if(edocRegister.getDistributeEdocId()!=-1) {
                		summary = edocManager.getEdocSummaryById(edocRegister.getDistributeEdocId(), true);
                		summary=cloneNewSummaryAndSetProperties(user.getName(), summary, orgAccountId, registerBody.getContentNo());
                		if(summary.isNew()) {
                			summary.setId(edocRegister.getDistributeEdocId());
                		}
                		atts = attachmentManager.getByReference(edocRegister.getDistributeEdocId(), edocRegister.getDistributeEdocId());
                	} else {
                		summary = new EdocSummary();                		
                		//登记正文	        		
                		String bodyContentType = null;
                	    EdocBody body = new EdocBody();
        	            if(null != registerBody) {
        	            	body.setContent(registerBody.getContent());
        	            	body.setContentNo(registerBody.getContentNo());
        	            	body.setContentType(registerBody.getContentType());
        	            	body.setCreateTime(registerBody.getCreateTime());
        	            	bodyContentType = body.getContentType();
        	            }
        	            if(null == bodyContentType) {
        	            	bodyContentType = Constants.EDITOR_TYPE_OFFICE_WORD;
        	            	if(com.seeyon.v3x.common.SystemEnvironment.hasPlugin("officeOcx")==false) {
        	                	bodyContentType=Constants.EDITOR_TYPE_HTML;
        	                }
        	            }
        	            body.setContentType(bodyContentType);
        	            summary.getEdocBodies().add(body);
        	            //登记单附件
                    	atts = attachmentManager.getByReference(registerId, registerId);
                    	
                     	BeanUtils.copyProperties(summary, edocRegister);
                     	summary=cloneNewSummaryAndSetProperties(user.getName(), summary, orgAccountId, registerBody.getContentNo());
                     	summary.setId(UUIDLong.longUUID());//以上操作将edocRegister的id赋值给summary的id，导致分发id与登记id一样
                	}    
            	} else {
            		if(Strings.isNotBlank(request.getParameter("distributeEdocId"))) {
            			long distributeEdocId = Long.parseLong(request.getParameter("distributeEdocId"));
            			summary = edocManager.getEdocSummaryById(distributeEdocId, true);
            			EdocBody body = new EdocBody();
            			if(summary == null) {
            				summary = new EdocSummary();
            			}
            			body = summary.getFirstBody();
                		summary=cloneNewSummaryAndSetProperties(user.getName(), summary, orgAccountId, body.getContentNo());
                		if(summary.isNew()) {
                			summary.setId(distributeEdocId);
                		}
                		atts = attachmentManager.getByReference(distributeEdocId, distributeEdocId);
            		}
            	}
            	
             	if(!Templete.Type.workflow.name().equals(templete.getType())){
             		summary.setFormId(((EdocSummary)XMLCoder.decoder(templete.getSummary())).getFormId());
             	}else{
             		defaultEdocForm=edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType);
		            summary.setFormId(defaultEdocForm.getId());
             	}

             	summary.setEdocType(EdocEnum.edocType.recEdoc.ordinal());
             	iEdocType=EdocEnum.edocType.recEdoc.ordinal();
             	modelAndView.addObject("strEdocId", strEdocId);
				//modelAndView.addObject("recSummaryId", registerId);
             	comm="distribute"; //不能去掉这个设置，页面分发调用模板的时候需要根据这个参数来过滤显示模板，
             	
             	canDeleteOriginalAtts = true;    //允许删除原附件
            } else{
				if(!Templete.Type.workflow.name().equals(templete.getType()))
				{
		            //不是通过交换进行登记，调用模板
					EdocBody body = (EdocBody)XMLCoder.decoder(templete.getBody());			
					summary = (EdocSummary)XMLCoder.decoder(templete.getSummary());
					summary.getEdocBodies().add(body);
					iEdocType=summary.getEdocType();
				}else{
					 //yangzd 读取上一次的非流程模板的正文
	    		    if(null!=oldtemplete&&Templete.Type.workflow.name().equals(oldtemplete.getType()))
	    			{
    					EdocBody body = (EdocBody)XMLCoder.decoder(oldtemplete.getBody());			
    					summary = (EdocSummary)XMLCoder.decoder(oldtemplete.getSummary());
    					summary.getEdocBodies().add(body);
    					iEdocType=summary.getEdocType();
	    			}
					else
					{
						//yangzd
						summary = new EdocSummary();
			            summary.setEdocType(iEdocType);
			            EdocBody body = new EdocBody();
			            String bodyContentType=Constants.EDITOR_TYPE_OFFICE_WORD;
			            if(com.seeyon.v3x.common.SystemEnvironment.hasPlugin("officeOcx")==false){bodyContentType=Constants.EDITOR_TYPE_HTML;}
			            body.setContentType(bodyContentType);
			            summary.getEdocBodies().add(body); 
			            summary.setCanTrack(1);
			            defaultEdocForm=edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType);
			            summary.setFormId(defaultEdocForm.getId());
					}
				}
				atts = attachmentManager.getByReference(templete.getId(), templete.getId());
				summary.setCreatePerson(user.getName());
				EdocHelper.reLoadAccountName(summary,EdocHelper.getI18nSeperator(request));
				canDeleteOriginalAtts = false;    //允许删除原附件
            }
			cloneOriginalAtts = true;
			if(summary != null){
				senderOpinion = summary.getSenderOpinion();
			}			
            edocFormId=summary.getFormId();
            summary.setOrgAccountId(user.getLoginAccount());
            summary.setTempleteId(Long.parseLong(templeteId));
            //检查模版公文单是否存在
            
	    	  if(null!=edocFormId)
	          {
	              if(defaultEdocForm==null){defaultEdocForm=edocFormManager.getEdocForm(edocFormId);}
	              if(defaultEdocForm==null){defaultEdocForm=edocFormManager.getDefaultEdocForm(summary.getOrgAccountId(),iEdocType);}
	          }
                    
            modelAndView.addObject("templete", templete);
            
            ColSuperviseDetail detail = colSuperviseManager.getSupervise(Constant.superviseType.template.ordinal(),id);
            if(detail != null) {
            	
            	Long terminalDate = detail.getTemplateDateTerminal();
            	if(null!=terminalDate){
            	Date superviseDate = Datetimes.addDate(new Date(), terminalDate.intValue());
            	//SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            	String date = Datetimes.format(superviseDate,Datetimes.datetimeWithoutSecondStyle);
            	detail.setAwakeDate(superviseDate);
            	modelAndView.addObject("superviseDate", date);
            	}
            	Set<ColSupervisor> supervisors = detail.getColSupervisors();
            	Set<String> sIdSet = new HashSet<String>();
            	StringBuffer ids = new StringBuffer();
            	StringBuffer names = new StringBuffer();
            	
            	for(ColSupervisor supervisor:supervisors){
            		sIdSet.add(supervisor.getSupervisorId().toString());
            	}
            	List<SuperviseTemplateRole> roleList = colSuperviseManager.findSuperviseRoleByTemplateId(templete.getId());
            	if((null!=roleList && !roleList.isEmpty()) || !sIdSet.isEmpty()){
            		modelAndView.addObject("sVisorsFromTemplate", "true");//公文调用的督办模板是否设置了督办人
            	}
            	V3xOrgRole orgRole = null;
            	
            	for(SuperviseTemplateRole role : roleList){
            		if(null==role.getRole() || "".equals(role.getRole())){
            			continue;
            		}
            		if(role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase())){
            			sIdSet.add(String.valueOf(user.getId()));
            		}
            		boolean haveManager = false;
            		
//            		yangzd

            		
            		if(role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER.toLowerCase())||role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase() + V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER.toLowerCase())){
            			orgRole = orgManager.getRoleByName(V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER, user.getLoginAccount());
            			if(null!=orgRole){
            			List<V3xOrgDepartment> depList = orgManager.getDepartmentsByUser(user.getId());
            			for(V3xOrgDepartment dep : depList){
            				List<V3xOrgMember> managerList = orgManager.getMemberByRole(V3xOrgEntity.ROLE_BOND_DEPARTMENT, dep.getId(), orgRole.getId());
            				for(V3xOrgMember mem : managerList){
            					haveManager = true;
                				sIdSet.add(mem.getId().toString());
                			}
            			}
            			}
            		}
            		else
            		{
            			modelAndView.addObject("isOnlySender", "true");
            		}
            		if(!haveManager){
            			modelAndView.addObject("noDepManager", "true");
            		}
//            		yangzd

            		if(role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase() + V3xOrgEntity.ORGENT_META_KEY_SUPERDEPMANAGER.toLowerCase())){
            			orgRole = orgManager.getRoleByName(V3xOrgEntity.ORGENT_META_KEY_SUPERDEPMANAGER, user.getLoginAccount());
            			if(null!=orgRole){
            			List<V3xOrgDepartment> depList = orgManager.getDepartmentsByUser(user.getId());
            			for(V3xOrgDepartment dep : depList){
            			List<V3xOrgMember> superManagerList = orgManager.getMemberByRole(V3xOrgEntity.ROLE_BOND_DEPARTMENT, dep.getId(), orgRole.getId());
               				for(V3xOrgMember mem : superManagerList){
               					sIdSet.add(mem.getId().toString());
               				}
            			}
            			}
            		}	
            	}
            	
            	for(String s : sIdSet){
            		V3xOrgMember mem = orgManager.getMemberById(Long.valueOf(s));
            		if(mem!=null){
            		ids.append(mem.getId());
            		ids.append(",");
            		names.append(mem.getName());
            		names.append(",");
            		}
            	}
            	
            	if(ids.length()>1 && names.length()>1){
            		modelAndView.addObject("colSupervisors", ids.substring(0, ids.length()-1));
            		detail.setSupervisors(names.substring(0, names.length()-1));
            	}
            	modelAndView.addObject("colSupervise", detail);
            }
            if("transmitSend".equals(request.getParameter("fromState")))
            {//转发调用模版操作
            	List<Attachment> attTemp=(List<Attachment>)request.getSession().getAttribute("transmitSendAtts");
            	if(attTemp!=null && attTemp.size()>0)
            	{
            		atts.addAll(attTemp);
            	}            	
            }
            //公文模板是否绑定了内部文号
            modelAndView.addObject("isBoundSerialNo",edocMarkDefinitionManager.getEdocMarkByTempleteId(Long.valueOf(templeteId), MarkCategory.serialNo)==null?false:true);
       }else if (s_summaryId != null) { // 来自待发
            long summaryId = Long.parseLong(s_summaryId);
            summary = edocManager.getEdocSummaryById(summaryId, true);
            iEdocType=summary.getEdocType();//修改待发，类型参数没有传递进来
            atts = attachmentManager.getByReference(summaryId, summaryId);            
            senderOpinion = summary.getSenderOpinion();//发起人附言
            String affairId = request.getParameter("affairId");
            try {
            	Affair affair = affairManager.getById(Long.parseLong(affairId));
            	if(affair != null &&  affair.getSubState() != null && affair.getSubState().equals(SubStateEnum.col_waitSend_sendBack.getKey())) {
            		modelAndView.addObject("fromSendBack", true);
            	}
            } catch(NumberFormatException nfe) {
            	affairId = "-1";
            }
            if (summary.getProcessId() != null) {
            	try {
            		process = EdocHelper.getRunningProcessByProcessId(summary.getProcessId());
            		
            		modelAndView.addObject("isForm", "false");
				}
				catch (Exception e) {
					log.error("", e);
				}
            }
			modelAndView.addObject("templateId", summary.getTempleteId());			
			if(summary.getTempleteId()!=null)
			{
				List<ColBranch> branchs = this.templeteManager.getBranchsByTemplateId(summary.getTempleteId(),ApplicationCategoryEnum.edoc.ordinal());
	            if(branchs != null) {
                    //显示分支条件使用流程中保留的，如果为空使用模板中的
	            	branchs = EdocHelper.updateBranchByProcess(summary.getProcessId(),branchs);
	            	modelAndView.addObject("branchs", branchs);
	            	modelAndView.addObject("teams", this.orgManager.getUserDomain(user.getId(), user.getLoginAccount(), V3xOrgEntity.ORGENT_TYPE_TEAM));
	            	V3xOrgMember mem = orgManager.getMemberById(user.getId());
	            	List<MemberPost> secondPosts = mem.getSecond_post();
	            	modelAndView.addObject("secondPosts", secondPosts);
	            }
	            
									
				Templete templete = templeteManager.get(summary.getTempleteId());
				isSystem = templete.getIsSystem();
				modelAndView.addObject("isFromTemplate", templete.getIsSystem());
				modelAndView.addObject("templateType",templete.getType());
				boolean sVisorsFromTemplate = false;
				ColSuperviseDetail detail = colSuperviseManager.getSupervise(Constant.superviseType.template.ordinal(), summary.getTempleteId());
				if(detail != null){
					sVisorsFromTemplate = (detail.getColSupervisors() != null && !detail.getColSupervisors().isEmpty());					
				}
				if(!sVisorsFromTemplate){					
					List<SuperviseTemplateRole> roleList = colSuperviseManager.findSuperviseRoleByTemplateId(summary.getTempleteId());
					sVisorsFromTemplate = (null!=roleList && !roleList.isEmpty());
				}
				modelAndView.addObject("sVisorsFromTemplate", sVisorsFromTemplate);//公文调用的督办模板是否设置了督办人
			}
            //affair = this.affairManager.getWaitSendBysummaryIdAndState(EdocUtil.getAppCategoryByEdocType(summary.getEdocType()), summaryId, StateEnum.col_waitSend.key());
            ColSuperviseDetail detail = colSuperviseManager.getSupervise(Constant.superviseType.edoc.ordinal(),summaryId);
          	modelAndView.addObject("fromSend", "true");
            if(detail != null) {
            	Set<ColSupervisor> supervisors = detail.getColSupervisors();
            	if(supervisors != null && supervisors.size()>0){
            		StringBuffer ids = new StringBuffer();
            		for(ColSupervisor supervisor:supervisors)
            			ids.append(supervisor.getSupervisorId() + ",");
            		modelAndView.addObject("colSupervisors", ids.substring(0, ids.length()-1));
            	}
            	modelAndView.addObject("colSupervise", detail);
            	modelAndView.addObject("superviseDate", Datetimes.format(detail.getAwakeDate(), Datetimes.datetimeWithoutSecondStyle));
            }
            
            edocFormId=summary.getFormId();
            //检查模版公文单是否存在
            defaultEdocForm=edocFormManager.getEdocForm(edocFormId);
            if(defaultEdocForm==null){defaultEdocForm=edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType);};
            //读取流程中的处理意见进行显示，待发中的公文有可能是回退、撤销到待发的，要显示历史处理过程中的意见
            //公文处理意见回显到公文单,排序
            LinkedHashMap lhs=edocManager.getEdocOpinion(summaryId, user.getId(),summary.getStartMember().getId());
            Hashtable hs=edocManager.getEdocOpinion(summary.getFormId(),lhs);
            String opinionsJs=EdocOpinionDisplayUtil.optionToJs(hs);
            modelAndView.addObject("opinionsJs",opinionsJs);
            //发起人意见
            modelAndView.addObject("senderOpinion",hs.get("senderOpinionList"));
            modelAndView.addObject("trackIds",getTrackIds(Strings.isNotBlank(affairId)?Long.valueOf(affairId):null));
            
            //归档可修改
            if(from!=null && "archived".equals(from)){
            	modelAndView.addObject("archivedModify",true);
            }
            if(iEdocType == 1) {//收文
            	edocRegister = edocRegisterManager.findRegisterByDistributeEdocId(summary.getId());
            	if(edocRegister != null) {
            		registerBody = edocRegisterManager.findRegisterBodyByRegisterId(edocRegister.getId());
            		registerId = edocRegister.getId();//登记id
            		edocRegister = null;
            	}
            	isFromWaitSend = true;
            }
            
        }else if("forwordtosend".equals(comm)){

        	String strEdocId=request.getParameter("edocId");//strEdocId变量获取需要处理的表单 
        	//如果是从待登记中进行转发文，会得到签收id
        	String recieveId = request.getParameter("recieveId"); 
        	if(Strings.isNotBlank(recieveId)){
        		modelAndView.addObject("recieveId", recieveId);
        	}
        	String forwordType = request.getParameter("forwordType");
        	if(Strings.isNotBlank(forwordType)){
        		modelAndView.addObject("forwordType", forwordType);
        	}
        	
          	checkOption=request.getParameter("checkOption");
          	/******** puyc 添加  关联收文的路径 *******/
			String relationUrl = this.relationReceive(strEdocId, "1");
			modelAndView.addObject("relationUrl", relationUrl);
			/******** puyc 添加 结束 *******/
          	Long edocId=0L;
          	modelAndView.addObject("forwordtosend", "1");//正文转附件后，第一次点击不提示正文已被修改
      	    String transmitSendNewEdocId=request.getParameter("transmitSendNewEdocId");
        	if(strEdocId!=null && !"".equals(strEdocId)){edocId=Long.parseLong(strEdocId);}
      	    Long orgAccountId=0L;
      	    EdocBody body = null;
      	    summary=edocManager.getEdocSummaryById(edocId,true); //获取Summary对象
      	    if(summary == null) {//如果来自待分发，传递的是登记单id
      	    	edocRegister = this.edocRegisterManager.getEdocRegister(edocId);
      	    	if(edocRegister != null) {
      	    		summary = new EdocSummary();
      	    		BeanUtils.copyProperties(summary, edocRegister);
      	    		registerBody = this.edocRegisterManager.findRegisterBodyByRegisterId(edocId);
      	    		if(registerBody != null) {
      	    			body = new EdocBody();
      	    			body.setContent(registerBody.getContent());
      	    			body.setContentType(registerBody.getContentType());
      	    			body.setCreateTime(registerBody.getCreateTime());
      	    			summary.setEdocBodies(new HashSet<EdocBody>());
      	    			summary.getEdocBodies().add(body);
      	    		}
      	    	}
      	    }
        	atts = excludeType2ToNewAttachmentList(summary);//获取所有附件
        	summary=cloneNewSummaryAndSetProperties(user.getName(), summary, orgAccountId,iEdocType);//克隆summary对象
        	//summary.setId(UUIDLong.longUUID());//以上操作将edocRegister的id赋值给summary的id，导致分发id与登记id一样
            defaultEdocForm=edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType);//获取默认公文单
	        summary.setFormId(defaultEdocForm.getId());//元素绑定表单
         	summary.setEdocType(EdocEnum.edocType.recEdoc.ordinal());
         	String subject=summary.getSubject();//获取原有标题
            body=summary.getFirstBody();//获取正文
            Date createDate = null;
            if(body !=null){
            	content=body.getContent();//获取正文ID，用来取原正文到新拟文单正文
                createDate = body.getCreateTime();
            }else{
            	content = "";
            }
            	
            cloneOriginalAtts=true;
            if(checkOption.equals("1") || checkOption.equals("0")){//正文转附件只取原文单标题,并将原有正文转为新公文附件
            	 summary=new EdocSummary();//产生新的表单对象，只保留原公文标题
            	 summary.setOrgAccountId(user.getLoginAccount());
                 summary.setEdocType(iEdocType);
                 summary.getEdocBodies().add(body); 
                 summary.setSubject(subject);
                 summary.setCanTrack(1);
                 summary.setCreatePerson(user.getName());
            	 if(checkOption.equals("1") && body.getContent()!=null){
            		//atts.add(edocSummaryManager.getAttsList(body, transmitSendNewEdocId, createDate, summary));
             		if(Constants.EDITOR_TYPE_OFFICE_EXCEL.equals(body.getContentType())
            				||Constants.EDITOR_TYPE_OFFICE_WORD.equals(body.getContentType())
            				||Constants.EDITOR_TYPE_WPS_WORD.equals(body.getContentType())
            				||Constants.EDITOR_TYPE_WPS_EXCEL.equals(body.getContentType())){//非html正文都以附件形势转发
            			InputStream in = null;
            			try { 
            				//查找清除了痕迹的公文。
            				Long srcFileId=Long.parseLong(body.getContent());
            				if(transmitSendNewEdocId!=null&&!"".equals(transmitSendNewEdocId))
            			    srcFileId=Long.parseLong(transmitSendNewEdocId);
            				String srcPath=fileManager.getFolder(createDate, true) + separator+ String.valueOf(srcFileId);
            				//1.解密文件
            				String newPath=CoderFactory.getInstance().decryptFileToTemp(srcPath);
            				//2.转换成标准正文
            				String newPathName = SystemEnvironment.getSystemTempFolder() + separator + String.valueOf(UUIDLong.longUUID());
            				Util.jinge2StandardOffice(newPath, newPathName);
            				//3.构造输入流
            				in = new FileInputStream(new File(newPathName)) ;
            				V3XFile f = fileManager.save(in, ApplicationCategoryEnum.edoc, summary.getSubject() + EdocUtil.getOfficeFileExt(body.getContentType()), createDate, false);
            				atts.add(new Attachment(f, ApplicationCategoryEnum.edoc, com.seeyon.v3x.common.filemanager.Constants.ATTACHMENT_TYPE.FILE));
            			}catch (Exception e) {
            				log.error("收文转发文错误 ", e);
            			}finally{
            				IOUtils.closeQuietly(in);
            			}
            		}else if(Constants.EDITOR_TYPE_PDF.equals(body.getContentType())){
            			String srcPath=fileManager.getFolder(createDate, true) + separator+ String.valueOf(body.getContent());
            			InputStream in = new FileInputStream(new File(srcPath)) ;
        				V3XFile f = fileManager.save(in, ApplicationCategoryEnum.edoc, summary.getSubject() + ".pdf", createDate, false);
        				atts.add(new Attachment(f, ApplicationCategoryEnum.edoc, com.seeyon.v3x.common.filemanager.Constants.ATTACHMENT_TYPE.FILE));
            		}else
            		{//html正文，先生成文件    			
            			V3XFile f =fileManager.save(body.getContent()==null?"":body.getContent(), ApplicationCategoryEnum.edoc, summary.getSubject()+".htm", createDate, false);    			
        				atts.add(new Attachment(f, ApplicationCategoryEnum.edoc, com.seeyon.v3x.common.filemanager.Constants.ATTACHMENT_TYPE.FILE));
            		}
            	}//将原有正文生成新公文附件 
            }else if(checkOption.equals("3")){
            	 int receive=1;
            	 modelAndView.addObject("ireive", receive);
            	 defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),receive);		
            }
        }else { //直接新建
            summary = new EdocSummary();
           //summary.setStartTime(new Timestamp(System.currentTimeMillis()));
            // lijl通过edoc_register的Id获取地象在发文单中显示----------------------------------开始
			String idStr = request.getParameter("id");
			Long id = 0L;
			if (idStr != null & !"".equals(idStr)) {
				id = Long.parseLong(idStr);
				/* puyc 分发 收文的summaryId */
				modelAndView.addObject("recSummaryId", idStr);
			}

			//组装分发正文和附件 wangjingjing begin
			EdocBody body = new EdocBody();
			String bodyContentType = null;
			if ("distribute".equals(comm)) {
				edocRegister = edocRegisterManager.findRegisterById(registerId);
				if(edocRegister != null) {
					//无权查看该主题
					if(user.getId()!=edocRegister.getDistributerId()) {
						Long agentMemberId = MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), edocRegister.getDistributerId());
			            if(agentMemberId == null) {
			            	PrintWriter out = response.getWriter();
			            	out.println("<script>");
			                out.println("alert('您无权查看该主题!');");
			                out.println("if(window.dialogArguments){"); // 弹出
			                out.println("   window.returnValue = \"true\";");
			                out.println("   window.close();");
			                out.println("} else {");
			                if("agent".equals(request.getParameter("app"))) {//无权查看主题，代理页面跳转到代理事项。
			                	out.println("	parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';");
			                } else {//无权查看主题，被代理页面跳转到代理事项。
			                	out.println("	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType="+edocType+"';");
			                }
			                out.println("}");
			                out.println("</script>");
			                return null;
			            }
					}
					//被撤销
					else if(edocRegister.getState()==EdocNavigationEnum.RegisterState.DraftBox.ordinal() || edocRegister.getState()==EdocNavigationEnum.RegisterState.deleted.ordinal()) {//被撤销
						String szJs = "<script>alert('公文《"+edocRegister.getSubject()+"》已经被撤销。');";
						if("agent".equals(request.getParameter("app")) && user.getId()!=edocRegister.getDistributerId()) {//代理进去
							szJs += "parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';";
						} else {
							szJs += "parent.parent.location.href='edocController.do?method=listIndex&from=listDistribute&edocType="+edocType+"'";
						}
						szJs += "</script>";
			        	response.getWriter().print(szJs);
			        	return null;
					} 
					//被退回
					else if(edocRegister.getState()==EdocNavigationEnum.RegisterState.retreat.ordinal()) {//被退回
						String szJs = "<script>alert('公文《"+edocRegister.getSubject()+"》已经被退回。');";
						if("agent".equals(request.getParameter("app")) && user.getId()!=edocRegister.getDistributerId()) {//代理进去
							szJs += "if(window.dialogArguments) {"; // 弹出
							szJs += "   window.returnValue = \"true\";";
							szJs += "   window.close();";
							szJs += "} else {";
							szJs += "	parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';";
							szJs += "}";
						} else {
							szJs += "if(window.dialogArguments) {"; // 弹出
							szJs += "   window.returnValue = \"true\";";
							szJs += "   window.close();";
							szJs += "} else {";
							szJs += "	parent.parent.location.href='edocController.do?method=listIndex&from=listDistribute&edocType="+edocType+"'";
							szJs += "}";
						}
						szJs += "</script>";
			        	response.getWriter().print(szJs);
			        	return null;
					} 
					//公文已经分发，不能进行重复分发。
					else if(edocRegister.getDistributeState() == 2) {
						String szJs = "<script>alert(\""+ResourceBundleUtil.getString("com.seeyon.v3x.exchange.resources.i18n.ExchangeResource","edoc.distributed")+"\");";
						if(user.getId()!=edocRegister.getDistributerId()) {//代理进去
							if("agent".equals(request.getParameter("app"))) {
								szJs += "if(window.dialogArguments) {"; // 弹出
								szJs += "   window.returnValue = \"true\";";
								szJs += "   window.close();";
								szJs += "} else {";
				                szJs += "	parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';";
				                szJs += "}";
							} else {
								szJs += "if(window.dialogArguments) {"; // 弹出
								szJs += "   window.returnValue = \"true\";";
								szJs += "   window.close();";
								szJs += "} else {";
								szJs += "	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType="+edocType+"'";
								szJs += "}";
							}
						} else {
							szJs += "if(window.dialogArguments) {"; // 弹出
							szJs += "   window.returnValue = \"true\";";
							szJs += "   window.close();";
							szJs += "} else {";
							szJs += "	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType="+edocType+"'";
							szJs += "}";
						}
						szJs += "</script>";
			        	response.getWriter().print(szJs);
			        	return null;
					}
				
					registerId = edocRegister.getId();//登记id
					registerBody = edocRegisterManager.findRegisterBodyByRegisterId(edocRegister.getId());
					
					//登记单附件
					atts = attachmentManager.getByReference(edocRegister.getId(), edocRegister.getId()); 
					BeanUtils.copyProperties(summary, edocRegister);
                 	summary.setId(UUIDLong.longUUID());//以上操作将edocRegister的id赋值给summary的id，导致分发id与登记id一样
		        	
					//登记单正文
					registerBody = edocRegisterManager.findRegisterBodyByRegisterId(edocRegister.getId());
		            if(null != registerBody){
		            	//BeanUtils.copyProperties(body, registerBody);   BeanUtils.copyProperties遇到空日期会报错，手动复制
		            	body.setContent(registerBody.getContent());
		            	body.setContentNo(registerBody.getContentNo());
		            	body.setContentType(registerBody.getContentType());
		            	body.setCreateTime(registerBody.getCreateTime());
		            	bodyContentType = body.getContentType();
		            }
		            cloneOriginalAtts = true;//正文是否要复制一份
					modelAndView.addObject("strEdocId", edocRegister.getEdocId());
				}
			}
			//组装分发正文和附件 wangjingjing end
			
			// lijl通过edoc_register的Id获取地象在发文单中显示----------------------------------结束
            summary.setOrgAccountId(user.getLoginAccount());
            summary.setEdocType(iEdocType); 
            
            if(null == bodyContentType){
            	bodyContentType = Constants.EDITOR_TYPE_OFFICE_WORD;
            	if(com.seeyon.v3x.common.SystemEnvironment.hasPlugin("officeOcx")==false)
                {
                	bodyContentType=Constants.EDITOR_TYPE_HTML;
                }
            }
            
            body.setContentType(bodyContentType);
            summary.getEdocBodies().add(body); 
            summary.setCanTrack(1);
            summary.setCreatePerson(user.getName());
            
			
			//会议纪要转发公文 --yangfan
			if(meetingSummaryId != null && !"".equals(meetingSummaryId)){
				MtSummaryCAP mtSummaryCAP = mtSummaryManagerCAP.getById(Long.parseLong(meetingSummaryId));
				//System.out.println("mtSummaryCAP.getMtName(): "+mtSummaryCAP.getMtName());
				summary.setSubject(mtSummaryCAP.getMtName());//set纪要标题到 公文标题
				//转发正文
				EdocBody body2 = new EdocBody();
	            String bodyContentType2=mtSummaryCAP.getDataFormat();
	            if(com.seeyon.v3x.common.SystemEnvironment.hasPlugin("officeOcx")==false){bodyContentType2=Constants.EDITOR_TYPE_HTML;}
	            body2.setContentType(bodyContentType2);
	            body2.setContent(mtSummaryCAP.getContent());
	            summary.getEdocBodies().add(body2); 
	            
	            List<Attachment> nowAtt= attachmentManager.getByReference(Long.parseLong(meetingSummaryId),Long.parseLong(meetingSummaryId));
	    		List<Attachment> exclude2List=new ArrayList<Attachment>();//需要重新new一个List，不能在atts的基础上使用remove.
	    		for(Attachment att:nowAtt){
	    			if(!Integer.valueOf(2).equals(att.getType()))
	    				exclude2List.add(att);
	    		}
	    		atts=exclude2List;
	            
			}
			//会议纪要转发公文 --yangfan
			
			
            if(iEdocType == 0) {
            	List<EdocCategory> categoryList = edocCategoryManager.getCategoryByAccount(user.getLoginAccount());
            	if(subType == -1) { 
            		//GOV-3490 【公文管理】-【发文管理】-【拟文】，进入拟文界面时循环弹出提示框'该类型下没找到公文单'
                    //依次找每个类型下的文单
            		for(int i=0;i<categoryList.size();i++){
            			edocCategory = categoryList.get(i);
            			//subType = edocCategory.getId();
            			defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType, subType);
            			if(defaultEdocForm != null){
            				break;
            			}
            		}
            		
//            		if(categoryList != null && categoryList.size()>0) {
//            			edocCategory = categoryList.get(0); 
//            			subType = edocCategory.getId();
//            			defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType, subType);
//            		}
            	} else {
            		edocCategory = edocCategoryManager.getCategoryById(subType); 
            		defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType, subType);
            		//当选择的文单类型下没有文单时，就要遍历所有文单类型依次查找了
            		//GOV-3490 【公文管理】-【发文管理】-【拟文】，进入拟文界面时循环弹出提示框'该类型下没找到公文单'
                    if(defaultEdocForm == null){
            			//依次找每个类型下的文单
                		for(int i=0;i<categoryList.size();i++){
                			edocCategory = categoryList.get(i);
                			subType = edocCategory.getId();
                			defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType, subType);
                			if(defaultEdocForm != null){
                				break;
                			}
                		}
            		}
            	}
            	modelAndView.addObject("subType", subType);
            }
            if(defaultEdocForm == null) {
        		defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),iEdocType);
        	}
            if(!"distribute".equals(comm)) {
				comm="new_form";//代表第一次保存
			}
        }   
        if(summary.getStartTime()==null){//自动带出拟文时间。
       	  summary.setStartTime(new Timestamp(System.currentTimeMillis()));
        }
        if(Strings.isBlank(summary.getSendUnit()) && Strings.isBlank(summary.getSendUnitId())){
        	summary.setSendUnit(EdocRoleHelper.getAccountById(user.getLoginAccount()).getName());
        	summary.setSendUnitId("Account|"+Long.toString(user.getLoginAccount()));
        }
        summary.setOrgAccountId(user.getLoginAccount());
    	//预归档
		Long archiveId = null;
        String archiveName = "";
        if(summary.getArchiveId() != null){
        	archiveId = summary.getArchiveId(); 
        	archiveName = docHierarchyManager.getNameById(archiveId);
        }
        modelAndView.addObject("archiveName", archiveName);
        long checkSendAclUserId = user.getId();//代理人可以登记
        if("distribute".equals(comm) || openTempleteOfExchangeRegist){
        	if(edocRegister!=null) {
        		checkSendAclUserId=edocRegister.getDistributerId();
        	}
        }
        //检查是否有公文发起权
        int roleEdocType = iEdocType==1?3:iEdocType;
        boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(summary.getOrgAccountId(),checkSendAclUserId,roleEdocType);
        //如果是阅转办，则允许直接转，不用判断是否有公文发起权--start--这种修改是临时的，发版后继续修改，阅转办存在数据结构问题
        if(checkOption.equals("3")){
        	isEdocCreateRole=true;
        }
      //如果是阅转办，则允许直接转，不用判断是否有公文发起权--end--这种修改是临时的，发版后继续修改，阅转办存在数据结构问题
       
        //检查是否有归档修改权
    	boolean edocCreateRole=EdocRoleHelper.isEdocCreateRole(summary.getOrgAccountId(),checkSendAclUserId,EdocEnum.edocType.archiveModifyEdoc.ordinal());
        if("archived".equals(from) ){//如果是从公文归档修改按钮进来的
        	if(!edocCreateRole){//但是没有公文归档修改权的提醒
    			modelAndView = new ModelAndView("common/redirect");
    			String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","alert_not_edocUPPwoer");
    			modelAndView.addObject("redirectURL",BaseController.REDIRECT_BACK);
    			modelAndView.addObject("errMsg",errMsg);
    			return modelAndView;
        	}
     	}else{
    		if(isEdocCreateRole==false && !"agent".equals(request.getParameter("app"))) {//没有公文发起权不能发送
    			modelAndView = new ModelAndView("common/redirect");
    			String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","alert_not_edoccreate");
    			modelAndView.addObject("redirectURL",BaseController.REDIRECT_BACK);
    			modelAndView.addObject("errMsg",errMsg);
    			return modelAndView;
    		}
    	}
        //页面显示的公文单列表。如果是模板，只取当前模板的。
        List <EdocForm> edocForms = null;
        String domainIds = null; 
        if(defaultEdocForm!=null){
        	edocFormId=defaultEdocForm.getId();
        	domainIds = orgManager.getUserIDDomain(user.getId(), V3xOrgEntity.VIRTUAL_ACCOUNT_ID, V3xOrgEntity.ORGENT_TYPE_ACCOUNT);
        	
        	// changyi add 如果是阅转办，那么在拟收文时只显示原来阅文对应的单子
        	String readToDeal = request.getParameter("pageview");
//        	if("listReading".equals(readToDeal)){
//        		edocForms = new ArrayList<EdocForm>();
//        		edocForms.add(defaultEdocForm);
//        	}else{
        		edocForms = getLoginAccountOrCurrentTempleteEdocForms(summary.getOrgAccountId(),domainIds,iEdocType,templeteId,edocFormId, templeteType, subType);
//        	}
        }
        if(edocForms==null || edocForms.size()<=0 || defaultEdocForm==null)
        {
        	String categoryName = "";
        	if(edocCategory != null) {
        		categoryName = edocCategory.getName();
        	}
        	String szJs="<script>alert(\""+ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","alert_nofind_edocForm")+"\");";
        	response.getWriter().print(szJs);
        	//当某类别下没有公文单时，提示之后，页面重新提交显示默认公文单
        	//修复bug GOV-3030 公文管理，公文类型下没有默认文单时，页面不跳转，空白页
        	//上面都遍历所有类型了，如果都没有文单就直接输出空白页
//        	response.getWriter().print("location.href='edocController.do?method=newEdoc&edocType=0'</script>");
        	
        	return null;
        }
    	
        modelAndView.addObject("registerId", registerId);
        modelAndView.addObject("edocForms",edocForms);
        modelAndView.addObject("attachments", atts);
        modelAndView.addObject("canDeleteOriginalAtts", canDeleteOriginalAtts);
        modelAndView.addObject("cloneOriginalAtts", cloneOriginalAtts);
        //modelAndView.addObject("affair", affair);
        if(process != null){
	        String caseProcessXML = process.toXML();
	        List<Party> workflowInfo = EdocHelper.getWorkflowInfo(process);	        
	        caseProcessXML = Strings.escapeJavascript(caseProcessXML);	        
	        modelAndView.addObject("hasWorkflow", true);        
	        modelAndView.addObject("process_xml", caseProcessXML);        
	        modelAndView.addObject("workflowInfo", workflowInfo);
	        modelAndView.addObject("isShowShortName", process.getIsShowShortName());
	        modelAndView.addObject("process_desc_by", FlowData.DESC_BY_XML);
		}
        
        Metadata remindMetadata = metadataManager.getMetadata(MetadataNameEnum.common_remind_time);
        Metadata  deadlineMetadata= metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline);
        modelAndView.addObject("remindMetadata", remindMetadata);
        modelAndView.addObject("deadlineMetadata", deadlineMetadata); 
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("appName",EdocEnum.getEdocAppName(iEdocType));
        modelAndView.addObject("templeteCategrory",EdocEnum.getTempleteCategory(iEdocType));        
        Metadata flowPermPolicyMetadata=null; 
        String defaultPerm="shenpi";
        if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("policy", "dengji");
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec"+Functions.suffix());
    		flowPermPolicyMetadata=metadataManager.getMetadata(MetadataNameEnum.edoc_rec_permission_policy);
    		//defaultPerm="shenpi"; //分发默认节点是审批
    	}
        else if(EdocEnum.edocType.sendEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("policy", "niwen");
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    		flowPermPolicyMetadata=metadataManager.getMetadata(MetadataNameEnum.edoc_send_permission_policy);
    	}  
    	else
    	{
    		modelAndView.addObject("policy", "niwen");
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    		flowPermPolicyMetadata=metadataManager.getMetadata(MetadataNameEnum.edoc_qianbao_permission_policy);
    	}
        modelAndView.addObject("defaultPermLabel", "node.policy."+defaultPerm);
        modelAndView.addObject("flowPermPolicyMetadata",flowPermPolicyMetadata);
        long actorId=-1;
        try{
        	if(!"archived".equals(from)){//归档可修改时，所有的公文元素都可以编辑，而不是根据节点权限来判断。actorId为-1时，所有元素都可编辑了。否则会以拟文节点权限来编辑
        	  actorId=flowPermManager.getFlowPerm(EdocUtil.getEdocMetadataNameEnum(iEdocType).name(),EdocUtil.getSendFlowpermNameByEdocType(iEdocType),summary.getOrgAccountId()).getFlowPermId();
            }
        }catch(Exception e)
        {
        	log.error("",e);
        }
        String exchangeId=null;
        if("distribute".equals(comm) || openTempleteOfExchangeRegist) {
        	/*if(record.getStatus()==com.seeyon.v3x.exchange.util.Constants.C_iStatus_Registered)
        	{//公文已经登记
        		modelAndView = new ModelAndView("common/redirect");
            	String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","alert_has_registe");
            	modelAndView.addObject("redirectURL",BaseController.REDIRECT_BACK);
            	modelAndView.addObject("errMsg",errMsg);
            	return modelAndView;
        	}        	*/
        	int contentNo = summary.getFirstBody().getContentNo();
        	if(registerBody != null) {
        		contentNo = registerBody.getContentNo().intValue();
        	}
        	if(contentNo == EdocBody.EDOC_BODY_SECOND) {
				summary.setSendUnit(summary.getSendUnit2());summary.setSendUnit2("");
				summary.setSendUnitId(summary.getSendUnitId2());summary.setSendUnitId2("");
				summary.setDocMark(summary.getDocMark2());summary.setDocMark2("");
				summary.setCopies(summary.getCopies2());summary.setCopies2(0);
				summary.setSendTo(summary.getSendTo2());summary.setSendTo2("");
				summary.setSendToId(summary.getSendToId2());summary.setSendToId2("");
				summary.setCopyTo(summary.getCopyTo2());summary.setCopyTo2("");
				summary.setCopyToId(summary.getCopyToId2());summary.setCopyToId2("");
				summary.setReportTo(summary.getReportTo2());summary.setReportTo2("");
				summary.setReportToId2(summary.getReportToId2());summary.setReportToId2("");
			}   
        }
        
        //校验sendUnitId数据是否正确
        if(!Strings.isBlank(summary.getSendUnitId()))
        {
        	if(summary.getSendUnitId().indexOf("|")<0){summary.setSendUnitId("Account|"+summary.getSendUnitId());}
        }
        if(!Strings.isBlank(summary.getSendUnitId2()))
        {
           	if(summary.getSendUnitId2().indexOf("|")<0){summary.setSendUnitId2("Account|"+summary.getSendUnitId2());}
        }
        
        EdocFormModel fm=null;
        if(StringUtils.isNotEmpty(templeteId)){
        	fm = edocFormManager.getEdocFormModel(edocFormId,summary,actorId,false,true);
        }else{
        	fm = edocFormManager.getEdocFormModel(edocFormId,summary,actorId);
        }
        summary.setIdIfNew();
        if(checkOption.equals("0") || checkOption.equals("3")){
        	if(content!=null && !"".equals(content)){
        		summary.getFirstBody().setContent(content);
            	fm.setEdocBody(summary.getFirstBody());
        	}
        }else if(checkOption.equals("1")){
        	//转发文，如果是正文作为附件转发过来，正文要清空，不作任何事
        }else{
        	fm.setEdocBody(summary.getFirstBody());
        }
        if("register".equals(comm) || "distribute".equals(comm) || openTempleteOfExchangeRegist) {        	
        	if(edocRegister!=null) {
        		//登记单正文
        		//组装分发正文和附件 wangjingjing begin
	            if(null!=registerBody && null!=registerBody.getContentNo()){
        			EdocBody edocBody = summary.getBody(registerBody.getContentNo().intValue());
        			if(null!=edocBody){
        				fm.setEdocBody(edocBody);
        			}else{
        				fm.setEdocBody(summary.getFirstBody());
        			}
        		}
	            canUpdateContent = (edocRegister.getRegisterType()==2||edocRegister.getRegisterType()==3) ? true : EdocSwitchHelper.canUpdateAtOutRegist();
        	} else {
	        	if(!Strings.isBlank(exchangeId)){        		
	        		if(null!=record && null!=record.getContentNo()){
	        			EdocBody edocBody = summary.getBody(record.getContentNo().intValue());
	        			if(null!=edocBody){
	        				fm.setEdocBody(edocBody);	
	        			}else{
	        				fm.setEdocBody(summary.getFirstBody());
	        			}     			
	        		}
	        	}
	        	canUpdateContent = EdocSwitchHelper.canUpdateAtOutRegist();
	        	summary.setNewId(); 
	        	fm.getEdocSummary().setNewId(); 
        	}
        	summary.setEdocOpinion(null);
        	summary.setEdocOpinions(null);
        	senderOpinion=null;
        }else if("transmitSend".equals(comm)){
        	summary.setNewId(); 
        	fm.getEdocSummary().setNewId();        	
        }
        fm.setEdocSummaryId(summary.getId());
        fm.setSenderOpinion(senderOpinion);
        fm.setDeadline(summary.getDeadline());
        modelAndView.addObject("formModel",fm);
        modelAndView.addObject("edocFormId",edocFormId);
        if(summary != null) {
        	modelAndView.addObject("contentRecordId", summary.getEdocBodiesJs());
        }
        if(isFromWaitSend) {
        	comm = "distribute";
        }
        modelAndView.addObject("comm",comm);
        //hasBody1,hasBody2:主要用途：联合发文有多套正文，判断是否存在套红后的多套正文
        
        if(summary != null) {
        	modelAndView.addObject("hasBody1", summary.getBody(1)!=null);
            modelAndView.addObject("hasBody2", summary.getBody(2)!=null);
        }
        modelAndView.addObject("selfCreateFlow",EdocSwitchHelper.canSelfCreateFlow());
        modelAndView.addObject("canUpdateContent",canUpdateContent);
        modelAndView.addObject("actorId",actorId);
        modelAndView.addObject("appType",EdocUtil.getAppCategoryByEdocType(iEdocType).getKey());
        modelAndView.addObject("personInput", EdocSwitchHelper.canInputEdocWordNum());
       
        String logoURL = EdocHelper.getLogoURL(summary.getOrgAccountId());
        modelAndView.addObject("logoURL", logoURL);
        modelAndView.addObject("standardDuration", standarduration == null?0:standarduration);
        
        
        if(edocRegister != null) {
        	if("agent".equals(request.getParameter("app"))) {
            	long affairId = Strings.isBlank(request.getParameter("affairId"))?-1:Long.parseLong(request.getParameter("affairId"));
            	if(affairId != -1) {
            		Affair affair = affairManager.getById(affairId);
            		if(affair!=null && affair.getMemberId()!=CurrentUser.get().getId()) {
            			if(affair.getApp() == 24) {//收文登记
            				boolean hasRegistButton = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.recEdoc.ordinal());
            				if(!hasRegistButton) {  
            					modelAndView.addObject("isAgent", true);
            				}
            			} else if(affair.getApp() == 34) {//收文分发
            				if(!isEdocCreateRole) {
            					modelAndView.addObject("isAgent", true);
            				}
            			}       			
            		}
            	} else {
            		modelAndView.addObject("isAgent", true);
            	}
            }
        }
        long distributeEdocId = summary.getId();
    	modelAndView.addObject("distributeEdocId", distributeEdocId);
        return modelAndView;
    }
    
    /** 新建登记单页面数据加载 -唐桂林 2011-10-12 */
    public ModelAndView newEdocRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView("edoc/newEdocRegister");               
        User user = CurrentUser.get();
        String comm = Strings.isBlank(request.getParameter("comm"))? "create" : request.getParameter("comm");//新建 /修改  
        int edocType = Strings.isBlank(request.getParameter("edocType"))? 1 : Integer.parseInt(request.getParameter("edocType"));
        long registerId = Strings.isBlank(request.getParameter("registerId")) ? -1 : Long.parseLong(request.getParameter("registerId"));
        long recieveId = Strings.isBlank(request.getParameter("recieveId")) ? -1 : Long.parseLong(request.getParameter("recieveId"));
        long exchangeId = Strings.isBlank(request.getParameter("exchangeId"))? -1 : Long.parseLong(request.getParameter("exchangeId"));
        long edocId = Strings.isBlank(request.getParameter("edocId"))? -1 : Long.parseLong(request.getParameter("edocId"));
        int registerType = Strings.isBlank(request.getParameter("registerType"))? EdocNavigationEnum.RegisterType.ByAutomatic.ordinal() : Integer.parseInt(request.getParameter("registerType"));
        long sendUnitId = Strings.isBlank(request.getParameter("sendUnitId")) ? -1 : Long.parseLong(request.getParameter("sendUnitId"));
        long affairId = Strings.isBlank(request.getParameter("affairId")) ? -1 : Long.parseLong(request.getParameter("affairId"));
        if(exchangeId != -1) {
        	recieveId = exchangeId;
        }
        
        /********* 关联发文 * 收文的Id,收文的Type*********/
        String relSends = "haveNot";  
        String relRecs = "haveNot";
        List<EdocSummary> newEdocList = this.edocSummaryRelationManager.findNewEdoc(edocId, user.getId(), 1);
        if(newEdocList != null){
        	 relSends = "haveMany";
        	 modelAndView.addObject("recEdocId",edocId); 
             modelAndView.addObject("recType",1);
             modelAndView.addObject("relSends",relSends);
        } 
        /********* 关联 发文的Id 发文的Type**********/
        
        
        EdocRegister edocRegister = null; 
        RegisterBody registerBody = null;
        List<Attachment> attachmentList = new ArrayList<Attachment>();
        EdocRecieveRecord record = null;
        long agentId = -1;//代理人
        long agentToId = -1;//被代理人  
        List<EdocMarkModel> serialNoList = new ArrayList<EdocMarkModel>();
        String strTemp = "";
        if("create".equals(comm)) {//新建
        	edocRegister = new EdocRegister();
	        //签收单
        	record = recieveEdocManager.getEdocRecieveRecord(recieveId);
        	//修复bug GOV-3204 公文管理-首页的BUG
        	Affair affair = affairManager.getById(affairId);
	        /**
	         * 登记公文，判断当前操作人是否可以登记此公文
	         */
	        //指定登记人
	        long registerUserId = record==null? user.getId(): record.getRegisterUserId();
	        //是否有登记权
	        //如果当前用户与登记用户不同，判断是代理人
	        if(registerUserId != user.getId()) {
	        	Long agentMemberId = MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), registerUserId);
	            if(agentMemberId != null) {
	            	agentId = Long.valueOf(agentMemberId);
		            agentToId = registerUserId;
		            if(user.getId() != agentId) {//如果当前用户与登记人的代理人不同，则表示公文登记人的代理人已转换
		                String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasChanged_register");
		                PrintWriter out = response.getWriter();
		                out.println("<script>");
		                out.println("alert(\"" + errMsg + "\");");
		                out.println("if(window.dialogArguments){"); // 弹出
		                out.println("   window.returnValue = \"true\";");
		                out.println("   window.close();");
		                out.println("} else {");
		                out.println("	parent.location.href='edocController.do?method=edocFrame&from=listRegister&edocType="+edocType+"';");
		                out.println("}");
		                out.println("</script>");
		                return null;
		            }
	            } else {
	            	PrintWriter out = response.getWriter();
	            	out.println("<script>");
	                out.println("alert('您无权查看该主题!');");
	                out.println("if(window.dialogArguments){"); // 弹出
	                out.println("   window.returnValue = \"true\";");
	                out.println("   window.close();");
	                out.println("} else {");
	                out.println("	parent.location.href='edocController.do?method=edocFrame&from=listRegister&edocType="+edocType+"';");
	                out.println("}");
	                out.println("</script>");
	                return null;
	            }
	        } 
	        //如果公文回退了
	        if(record!=null && (record.getStatus() == com.seeyon.v3x.exchange.util.Constants.C_iStatus_Torecieve || (record.getIsRetreat()==1))) {
	            String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasBeStepBack_already");
	            PrintWriter out = response.getWriter();
	            out.println("<script>");
	            out.println("alert(\"" + errMsg + "\");");
	            out.println("if(window.dialogArguments){"); // 弹出
	            out.println("  window.returnValue = \"true\";");
	            out.println("  window.close();");
	            out.println("}else{");
	            out.println("	parent.location.href='edocController.do?method=edocFrame&from=listRegister&edocType="+edocType+"';");
	            out.println("}");
	            out.println("");
	            out.println("</script>");
	            return null;
	        }
	        //修复bug GOV-3204 公文管理-首页的BUG
	        //当公文已经登记后，再待分发中退回时，并没有对签收表中的状态进行改变，而且affair的状态为3,表示待处理的状态，因此首页能够显示出它属于
	        //待登记的状态，因此这里再加上 affair的状态判断，这种情况就可以进行处理了
	        boolean hasRegisted = false;
	        if(affair!=null) {
	        	// 公文已经登记
	        	if(affair.getState() != StateEnum.col_pending.key()) {
			        if (record!=null && record.getStatus() == com.seeyon.v3x.exchange.util.Constants.C_iStatus_Registered) {
			        	hasRegisted = true;
			        }	        
	        	}
	        } else {
	        	if (record!=null && record.getStatus() == com.seeyon.v3x.exchange.util.Constants.C_iStatus_Registered) {
	        		hasRegisted = true;
	        	}
	        }
	        if(hasRegisted) {
		        modelAndView = new ModelAndView("common/redirect");
	            String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_has_registe");
	            modelAndView.addObject("redirectURL", BaseController.REDIRECT_BACK);
	            PrintWriter out = response.getWriter();
	            out.println("<script>");
	            out.println("alert(\"" + errMsg + "\")");
	            out.println("if(window.dialogArguments){"); // 弹出
	            out.println("  window.returnValue = \"true\";");
	            out.println("  window.close();");
	            out.println("} else {");
	            if("agent".equals(request.getParameter("app")) && user.getId()!=record.getRegisterUserId()) {//代理人跳转到代理事项
	            	out.println("parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';");
	            } else {
	            	out.println("parent.parent.location.href='edocController.do?method=listIndex&from=listRegister&listType=registerDone&edocType="+edocType+"'");
	            }		            
	            out.println("}");
	            out.println("");
	            out.println("</script>");
	            return null;
	        }
	        
	        //装载数据到登记表
	        edocRegister.setId(-1L);
	      /*  if(agentToId != -1){
	        	edocRegister.setCreateUserId(agentToId);
		        edocRegister.setCreateUserName(orgManager.getMemberById(agentToId).getName());
	        }else{
	        */
	        	edocRegister.setCreateUserId(user.getId());
		        edocRegister.setCreateUserName(user.getName());
	       // }
	        edocRegister.setCreateTime(new java.sql.Timestamp(new Date().getTime()));
	        edocRegister.setUpdateTime(new java.sql.Timestamp(new Date().getTime()));
	        edocRegister.setOrgAccountId(user.getAccountId());
	        edocRegister.setState(EdocNavigationEnum.RegisterState.WaitRegister.ordinal());
	        //设置登记人
	        edocRegister.setRegisterUserId(registerUserId);
	        V3xOrgMember v3xOrgMember = orgManager.getMemberById(registerUserId);
	        edocRegister.setRegisterUserName(v3xOrgMember==null ? user.getName() : v3xOrgMember.getName());
	        //设置默认分发人      
	       if(registerUserId != user.getId()) {
	    	   edocRegister.setDistributerId(registerUserId);
	    	   edocRegister.setDistributer(orgManager.getMemberById(registerUserId).getName());
	       } else {
	    	   edocRegister.setDistributerId(user.getId());
		       edocRegister.setDistributer(user.getName());
	       }
	        edocRegister.setRegisterType(registerType);
	        edocRegister.setRegisterDate(new java.sql.Date(new Date().getTime()));
	        //来文信息
	        edocRegister.setEdocId(edocId);
	        edocRegister.setRecieveId(recieveId);
	        V3xOrgAccount account = orgManager.getAccountById(sendUnitId);
	        edocRegister.setSendUnit(account==null?"":account.getName());
	        edocRegister.setSendUnitId(sendUnitId);
	        edocRegister.setSendUnitType(record==null? 1 : record.getSendUnitType());
	        edocRegister.setEdocType(EdocEnum.edocType.recEdoc.ordinal());
	        edocRegister.setDocType(record==null? "1" : record.getDocType());
	        edocRegister.setSubject(record==null? "" : record.getSubject());
	        edocRegister.setDocMark(record==null? "" : record.getDocMark());
	        edocRegister.setSecretLevel(record==null? "1" : record.getSecretLevel());
	        edocRegister.setUrgentLevel(record==null? "1" : record.getUrgentLevel());
	        //lijl添加,GOV-3061.收文管理-登记的时候，怎么没有把主送单位带进来呢？
	        //增加主送单位
	        edocRegister.setSendTo(record==null? "":record.getSendTo());
	        //公文元素基本信息
	        //从EdocSummary对象中取的数据
	        EdocSummary summary = edocManager.getEdocSummaryById(edocId, true);
	        edocRegister.setKeepPeriod(summary==null? record==null?"":record.getKeepPeriod() : String.valueOf(summary.getKeepPeriod()));
	        edocRegister.setSendType(summary==null? "1" : summary.getSendType());
	        edocRegister.setKeywords(summary==null? "" : summary.getKeywords());
	        edocRegister.setIssuerId(-1);
	        edocRegister.setIssuer(summary==null? "" : summary.getIssuer());
	        edocRegister.setEdocDate(summary==null? null : summary.getSigningDate());
	        if(edocRegister.getEdocDate()==null) {//如果没有签发时间，则显示为封发时间
	            edocRegister.setEdocDate(summary==null ? null : new java.sql.Date(summary.getPackTime().getTime()));
	        }
	        
	        //附件信息
	        if(summary != null) {
	        	attachmentList = attachmentManager.getByReference(summary.getId(), summary.getId());
	        }
	        edocRegister.setIdentifier("00000000000000000000");
	        edocRegister.setAttachmentList(attachmentList);
	        edocRegister.setHasAttachments(attachmentList.size()>0);
	        //装载公文正文
	        if(summary !=null && record!=null) {
	        	EdocBody edocBody = summary.getBody(record.getContentNo().intValue());
	        	registerBody = new RegisterBody();
	        	edocBody = edocBody==null?summary.getFirstBody() : edocBody;
				if(null != edocBody){
					registerBody.setId(-1L);
					registerBody.setContent(edocBody.getContent());
					registerBody.setContentNo(edocBody.getContentNo());
					registerBody.setContentType(edocBody.getContentType());
					registerBody.setCreateTime(edocBody.getLastUpdate());
					edocRegister.setRegisterBody(registerBody);	
				}
	        } else {
	        	registerBody = new RegisterBody();
	        	String bodyContentType=Constants.EDITOR_TYPE_OFFICE_WORD;
	            if(com.seeyon.v3x.common.SystemEnvironment.hasPlugin("officeOcx")==false) {
	            	bodyContentType = Constants.EDITOR_TYPE_HTML;
	            }
	            registerBody.setId(-1L);
	        	registerBody.setContentType(bodyContentType);
	        	registerBody.setCreateTime(new java.sql.Timestamp(new java.util.Date().getTime()));
	            edocRegister.setRegisterBody(registerBody);
	        }
	        if(summary!=null && !Strings.isBlank(summary.getSendUnit()) && !Strings.isBlank(summary.getSendUnitId())) {
	            edocRegister.setEdocUnit(summary.getSendUnit());
	            edocRegister.setEdocUnitId(summary.getSendUnitId());
	        }
	        
	        edocRegister.setSerialNo("");
        } else {//修改
        	edocRegister = edocRegisterManager.getEdocRegister(registerId);
        	if(edocRegister == null) {//该登记不存在
        		String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_edocregister_isnotexsit");
                PrintWriter out = response.getWriter();
                out.println("<script>");
                out.println("alert(\"" + errMsg + "\")");
                out.println("if(window.dialogArguments){"); // 弹出
                out.println("   window.returnValue = \"true\";");
                out.println("   window.close();");
                out.println("} else {");
                out.println("   parent.location.href='edocController.do?method=edocFrame&from=listRegister&edocType="+edocType+"'");
                out.println("}");
                out.println("</script>");
                return null;
	        }
        	
        	if(Strings.isNotBlank(edocRegister.getSerialNo())) {
		        EdocMarkModel emTemp=null;
				try{emTemp=EdocMarkModel.parse(edocRegister.getSerialNo());}catch(Exception e){}
				if(emTemp==null) {
					emTemp = new EdocMarkModel();
					emTemp.setMark(Strings.toHTML(Strings.toXmlStr(edocRegister.getSerialNo())));
					emTemp.setWordNo("0|" + Strings.toHTML(Strings.toXmlStr(edocRegister.getSerialNo()),false) + "||" + com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_NONE);
				} else {
					strTemp = emTemp.getMarkDefinitionId() + "|" + emTemp.getMark() + "|" + emTemp.getCurrentNo() + "|" + com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_NEW;
					emTemp.setMark(Strings.toHTML(Strings.toXmlStr(edocRegister.getSerialNo())));
					emTemp.setWordNo(Strings.toHTML(Strings.toXmlStr(strTemp)));
				}
		        serialNoList.add(emTemp);
        	}
        	registerBody = edocRegisterManager.findRegisterBodyByRegisterId(registerId);
        	attachmentList = attachmentManager.getByReference(edocRegister.getId(), edocRegister.getId());
	        edocRegister.setAttachmentList(attachmentList);
        }
        Long _orgAccountId=V3xOrgEntity.VIRTUAL_ACCOUNT_ID;
        String deptIds = orgManager.getUserIDDomain(CurrentUser.get().getId(),_orgAccountId, V3xOrgEntity.ORGENT_TYPE_DEPARTMENT, V3xOrgEntity.ORGENT_TYPE_ACCOUNT);
        EdocMarkModel markModel = null;
        List<EdocMarkModel> list = edocMarkDefinitionManager.getEdocMarkDefinitions(deptIds, EdocEnum.MarkType.edocInMark.ordinal());
    	if (list != null && list.size()>0) {
			for(int x=0;x<list.size();x++){
				markModel = (EdocMarkModel)list.get(x);
				if (null != markModel) {					
					Long definitionId = markModel.getMarkDefinitionId();
					strTemp = definitionId + "|" + markModel.getMark() + "|" + markModel.getCurrentNo() + "|" + com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_NEW;
					if(strTemp.equals(edocRegister.getSerialNo())){continue;}
					markModel.setMark(Strings.toHTML(Strings.toXmlStr(markModel.getMark())));
					markModel.setWordNo(Strings.toHTML(Strings.toXmlStr(strTemp)));
					serialNoList.add(markModel);
				}
			}
		}
        /** 基础信息装载 */
        modelAndView.addObject("comm", comm);
        modelAndView.addObject("affairId", affairId);
        modelAndView.addObject("agentId", agentId);
        modelAndView.addObject("agentToId", agentToId);
        modelAndView.addObject("oldDistributerId", edocRegister.getDistributerId());
        modelAndView.addObject("controller", "edocController.do");
        /** 权限信息装载 */
        boolean canDeleteOriginalAtts = true;//是否能删除附件
        boolean cloneOriginalAtts = "create".equals(comm) && record!=null;//是否能复制正文
        boolean canUpdateContent = (edocRegister.getRegisterType()==2||edocRegister.getRegisterType()==3) ? true : EdocSwitchHelper.canUpdateAtOutRegist();;//是否能修改正文
        modelAndView.addObject("canDeleteOriginalAtts", canDeleteOriginalAtts);
        modelAndView.addObject("cloneOriginalAtts", cloneOriginalAtts);
        modelAndView.addObject("personInput", EdocSwitchHelper.canInputEdocWordNum());
        modelAndView.addObject("canUpdateContent", canUpdateContent);
        /** 枚举信息装载 */ 
        Metadata remindMetadata = metadataManager.getMetadata(MetadataNameEnum.common_remind_time);
        Metadata deadlineMetadata = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline);
        modelAndView.addObject("remindMetadata", remindMetadata);
        modelAndView.addObject("deadlineMetadata", deadlineMetadata);
        modelAndView.addObject("appName", EdocEnum.getEdocAppName(edocType));
        modelAndView.addObject("templeteCategrory", EdocEnum.getTempleteCategory(edocType));
        Metadata sendUnitTypeData = metadataManager.getMetadata(MetadataNameEnum.send_unit_type);//来文类别
        Metadata edocSecretLevelData = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);//密级程度
        Metadata edocUrgentLevelData = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);//紧急程度
        Metadata edocKeepPeriodData = metadataManager.getMetadata(MetadataNameEnum.edoc_keep_period);//保密期限
        modelAndView.addObject("sendUnitTypeData", sendUnitTypeData);
        modelAndView.addObject("edocSecretLevelData", edocSecretLevelData);
        modelAndView.addObject("edocUrgentLevelData", edocUrgentLevelData);
        modelAndView.addObject("edocKeepPeriodData", edocKeepPeriodData);
        modelAndView.addObject("serialNoList", serialNoList);
        /** 对象装载 */
        modelAndView.addObject("bean", edocRegister);
        modelAndView.addObject("registerBody", registerBody);
        modelAndView.addObject("attachments", edocRegister.getAttachmentList());
        modelAndView.addObject("forwordtosend", "1");//登记单打开正文的js中用  wangjingjing
        //lijl添加appType----------GOV-2225.公文管理-收文管理-登记-待登记页面，打开一条公文进行登记，不能插入关联文档，不正确。
        int iEdocType=-1;
        String edocType1=request.getParameter("edocType");
        if(edocType1!=null && !"".equals(edocType1))
        {
        	iEdocType=Integer.parseInt(edocType1);
        }   
        modelAndView.addObject("appType",EdocUtil.getAppCategoryByEdocType(iEdocType).getKey());
        return modelAndView;
    }  
    
    /** 保存登记单 -唐桂林2011-10-12 */
    public ModelAndView saveRegister(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String comm = Strings.isBlank(request.getParameter("comm"))? "create" : request.getParameter("comm");//新建 /修改
        String listType = Strings.isBlank(request.getParameter("listType"))? "listRegister" : request.getParameter("listType");//新建 /修改 
        long registerId = Strings.isBlank(request.getParameter("id")) ? -1L : Long.parseLong(request.getParameter("id"));
        long agentId = Strings.isBlank(request.getParameter("agentId"))? -1 : Long.parseLong(request.getParameter("agentId"));//代理人id
        long agentToId = Strings.isBlank(request.getParameter("agentToId")) ? -1 : Long.parseLong(request.getParameter("agentToId"));//代理人id
        long oldDistributerId = Strings.isBlank(request.getParameter("oldDistributerId"))? -1 : Long.parseLong(request.getParameter("oldDistributerId"));//原来的分发人
        EdocRegister edocRegister = edocRegisterManager.getEdocRegister(registerId);
        RegisterBody registerBody = edocRegisterManager.findRegisterBodyByRegisterId(registerId);

        User user = CurrentUser.get(); 
        if(edocRegister == null) {
    		edocRegister = new EdocRegister(); 
    	}
        /*******************/
        if(registerBody == null) {
        	registerBody = new RegisterBody();
        }
        edocRegister.bind(request);
    	registerBody.bind(request);
    	//删除原有附件
        if(!edocRegister.isNew()) {
            this.attachmentManager.deleteByReference(edocRegister.getId());
        } else {
        	edocRegister.setNewId();
            registerBody.setNewId();
        }
        // 保存附件
        String attaFlag = this.attachmentManager.create(ApplicationCategoryEnum.edocRegister, edocRegister.getId(), edocRegister.getId(), request);
        if(com.seeyon.v3x.common.filemanager.Constants.isUploadLocaleFile(attaFlag)) {
            edocRegister.setHasAttachments(true);
        }
             
        //修改签收单
        EdocRecieveRecord edocRecieveRecord = recieveEdocManager.getEdocRecieveRecord(edocRegister.getRecieveId());
        edocRegister.setRegisterUserId(edocRecieveRecord==null?user.getId():edocRecieveRecord.getRegisterUserId());
        edocRegister.setRecTime(edocRecieveRecord==null?null:edocRecieveRecord.getRecTime());
        
        if(edocRegister.getState() == 2) {//状态为已登记
        	edocRegister.setIsRetreat(0);//非退回
        	edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.WaitDistribute.ordinal());
        }
        
        String serialNo = edocRegister.getSerialNo();
        serialNo = this.registDocMark(edocRegister.getId(), serialNo, 3, 1, false, EdocEnum.MarkType.edocInMark.ordinal());
        if(serialNo!=null){edocRegister.setSerialNo(serialNo);}
        
        if("create".equals(comm)) {
        	registerBody.setEdocRegister(edocRegister);
        	edocRegister.setRegisterBody(registerBody);
            edocRegisterManager.createEdocRegister(edocRegister);
            //电子公文
            if(edocRegister.getRegisterType() == 1) {
            	recieveEdocManager.registerRecieveEdoc(edocRegister.getRecieveId());
            }            
        } else {
        	registerBody.setEdocRegister(edocRegister);
        	edocRegister.setRegisterBody(registerBody);
        	edocRegisterManager.updateEdocRegister(edocRegister);
        } 
        
        if(edocRecieveRecord!=null) {
	        edocRecieveRecord.setStatus(EdocNavigationEnum.RegisterState.Registed.ordinal());
	        edocRecieveRecord.setRegisterTime(new java.sql.Timestamp(edocRegister.getRegisterDate().getTime()));
	        edocRecieveRecord.setRegisterName(edocRegister.getRegisterUserName());
	        
	        recieveEdocManager.update(edocRecieveRecord);
	        if(edocRegister.getState() == 2) {
	        	//去掉待登记
	        	Map<String, Object> params = new HashMap<String, Object>();
	        	//wangjingjing begin
	        	params.put("app", ApplicationCategoryEnum.edocRegister.getKey());
	        	//wangjingjing end
	        	params.put("objectId", edocRecieveRecord.getEdocId());
		        List<Affair> affairList = affairManager.getByConditions(params);
		        if(affairList!=null) {
		        	for(int i=0; i<affairList.size(); i++) {
		        		//代理人登记
		        		if(user.getId() != edocRegister.getRegisterUserId()){
		        			affairList.get(i).setTransactorId(user.getId());
		        		}
		        		affairList.get(i).setState(StateEnum.edoc_exchange_registered.getKey());
		        		affairManager.updateAffair(affairList.get(i));
		        	}
		        }
		        //xiangfan 添加日志GOV-1206
		        appLogManager.insertLog(user, AppLogAction.Edoc_RegEdoc, user.getName(),edocRegister.getSubject());
	        }
        }
        
  
        //发送消息
       
        if(edocRegister.getState() == 2) {  
        	//-------------待分发列表没有显示word图标bug 修复  changyi update
        	sendMessageToRegister(user, agentId, edocRegister, comm, oldDistributerId, registerBody.getContentType());	
        }
        
        //页面跳转
        PrintWriter out = response.getWriter();
        out.println("<script>");
        
        if("agent".equals(request.getParameter("app")) && user.getId()!=edocRegister.getRegisterUserId()) {//代理人跳转到代理事项
        	out.println("if(window.dialogArguments){"); // 弹出
            out.println("   window.returnValue = \"true\";");
            out.println("   window.close();");
            out.println("} else {");
        	out.println("parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';");
        	out.println("}");
        } else {
        	int state = EdocNavigationEnum.RegisterListState.getEnumByKey(listType).getValue();
        	if("create".equals(comm) || (state==0 && edocRegister.getState()!=0)) {//从草稿箱中进入，页面跳转同新建
        		if(edocRegister.getState() == EdocNavigationEnum.RegisterState.DraftBox.ordinal()) {//草稿
        			out.println("if(window.dialogArguments){"); // 弹出
                    out.println("   window.returnValue = \"true\";");
                    out.println("   window.close();");
                    out.println("} else {");
    				out.println("	parent.parent.window.location.href='edocController.do?method=listIndex&edocType=1&from=listRegister&listType=registerDraft';");
    				out.println("}");
    			} else {
    				out.println("if(window.dialogArguments){"); // 弹出
                    out.println("   window.returnValue = \"true\";");
                    out.println("   window.close();");
                    out.println("} else {");
    				out.println("	parent.parent.window.location.href='edocController.do?method=listIndex&edocType=1&from=listRegister&listType=registerDone';");
    				out.println("}");
    			}
        	} else {
        		out.println("if(window.dialogArguments){"); // 弹出
                out.println("   window.returnValue = \"true\";");
                out.println("   window.close();");
                out.println("} else {");
        		out.println("	parent.parent.window.location.href='edocController.do?method=listIndex&edocType=1&from=listRegister&listType="+listType+"';");
        		out.println("}");
        	}        	        	
        }
        out.println("</script>");
        return null;
    }
    
    //登记后发送消息
    private void sendMessageToRegister(User user, long agentToId, EdocRegister edocRegister, String comm, long oldDistributerId,String...bodyType) throws MessageException {
		try {
	    	String key = "edoc.registered"; //成功登记
	    	String register = "exchange.edoc.register";
			String cancel = "edoc.registered.distribute.cancel"; //撤销
			String modify = "edoc.registered.modify"; //撤销
			String userName = user.getName();
			long userId = user.getId();
			long registerId = edocRegister.getId();
			long registerUserId = edocRegister.getRegisterUserId();
			long distributerId = edocRegister.getDistributerId();
			String subject = edocRegister.getSubject();
			String url = "message.link.exchange.registered.GOV"; 
			String agentApp = "agent";
			com.seeyon.v3x.common.usermessage.Constants.LinkOpenType linkOpenType = com.seeyon.v3x.common.usermessage.Constants.LinkOpenType.href;
			String agentToName = "";
			String registerName = "";
			V3xOrgMember member = orgManager.getMemberById(edocRegister.getRegisterUserId());
			if(member!=null) {
				registerName = member.getName();
			}
			if("modify".equals(comm)) {
				//如果修改了分发人
				if(distributerId != oldDistributerId) {
					//给分发人发送修改消息
					distributeAffair(subject, registerUserId, oldDistributerId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "delete");
					sendRegisterMessage(cancel , subject, registerName, agentToName, userId, registerId, oldDistributerId, "", "", null, linkOpenType, -1L, "");
					//给分发人代理发送修改消息
					Long agentMemberId =  MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), oldDistributerId); 
					if(agentMemberId != null){
						//distributeAffair(subject, registerUserId, agentMemberId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "delete");
						sendRegisterMessage(cancel , subject, registerName, agentToName, userId, registerId, agentMemberId, "col.agent", "", null, linkOpenType, -1L, agentApp);
					}
					//给分发人发消息  [登记人]登记了公文《》，请速进行分发处理！
					distributeAffair(subject, registerUserId, distributerId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create");
					sendRegisterMessage(key , subject, registerName, agentToName, userId, registerId, distributerId, "", "", url, linkOpenType, registerId, "");
					//给分发人的代理人发消息
					agentMemberId =  MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), distributerId); 
					if(agentMemberId != null){
						//distributeAffair(subject, registerUserId, agentMemberId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create");
						sendRegisterMessage(key , subject, registerName, agentToName, userId, registerId, agentMemberId, "col.agent", "", url, linkOpenType, registerId, agentApp);
					}
				} else {
					//给分发人发送修改消息
					distributeAffair(subject, registerUserId, oldDistributerId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create");
					sendRegisterMessage(modify , subject, registerName, agentToName, userId, registerId, distributerId, "", "", url, linkOpenType, registerId, "");
					//给分发人代理发送修改消息
					Long agentMemberId =  MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), distributerId); 
					if(agentMemberId != null){
						//distributeAffair(subject, registerUserId, agentMemberId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create");
						sendRegisterMessage(modify , subject, registerName, agentToName, userId, registerId, agentMemberId, "col.agent", "", url, linkOpenType, registerId, agentApp);
					}
				}
			} else {
				//代理人登记
				if(agentToId != -1){
					try{
						agentToName = userName;
					} catch(Exception e) {
						log.error(e);
					}
					//给分发人发消息   [登记人]成功登记公文《》，请速进行分发处理！(由代理人[]代为处理)
					distributeAffair(subject, registerUserId, distributerId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create",bodyType);
					sendRegisterMessage(key , subject, registerName, agentToName, agentToId, registerId, distributerId, "", "edoc.agent.deal", url, linkOpenType, registerId, "");
					//给分发人代理人发消息   [登记人]成功登记公文《》，请速进行分发处理！(由代理人[]代为处理)(代理)
					Long agentMemberId =  MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), distributerId); 
					if(agentMemberId != null){
						//distributeAffair(subject, registerUserId, agentMemberId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create");
						sendRegisterMessage(key , subject, registerName, agentToName, agentToId, registerId, agentMemberId, "col.agent", "edoc.agent.deal", url, linkOpenType, registerId, agentApp);
					}
					url = "message.link.exchange.registered";
					//给登记被代理人发消息  [登记人]登记了公文《》
					MessageContent msgContent = new MessageContent("exchange.edoc.register", registerName, subject);
					msgContent.add("edoc.agent.deal", user.getName());
					msgContent.setResource("com.seeyon.v3x.exchange.resources.i18n.ExchangeResource");
					MessageReceiver receiver =new MessageReceiver(registerId, edocRegister.getRegisterUserId(), url, registerId+"");
					userMessageManager.sendSystemMessage(msgContent,ApplicationCategoryEnum.edoc, agentToId, receiver);
					//sendRegisterMessage(register , subject, registerName, agentToName, agentToId, registerId, edocRegister.getRegisterUserId(), "", "edoc.agent.deal", url, linkOpenType, registerId, "", "com.seeyon.v3x.exchange.resources.i18n.ExchangeResource");
					Long agentRegisterMemberId =  MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), edocRegister.getRegisterUserId()); 
					if(agentRegisterMemberId != null){
						//sendRegisterMessage(register , subject, registerName, agentToName, agentToId, registerId, agentRegisterMemberId, "col.agent", "edoc.agent.deal", url, linkOpenType, registerId, agentApp, "com.seeyon.v3x.exchange.resources.i18n.ExchangeResource");
						msgContent = new MessageContent("exchange.edoc.register", registerName, subject);
						msgContent.add("col.agent");
						msgContent.add("edoc.agent.deal", user.getName());
						msgContent.setResource("com.seeyon.v3x.exchange.resources.i18n.ExchangeResource");
						receiver = new MessageReceiver(registerId, agentRegisterMemberId, url, registerId+"");
						userMessageManager.sendSystemMessage(msgContent,ApplicationCategoryEnum.edoc, agentRegisterMemberId, receiver);
					}
					
				}else{//非代理人登记
					//给分发人发消息  [登记人]登记了公文《》，请速进行分发处理！
					distributeAffair(subject, registerUserId, distributerId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create",bodyType);
					sendRegisterMessage(key , subject, registerName, agentToName, userId, registerId, distributerId, "", "", url, linkOpenType, registerId, "");
					//给分发人的代理人发消息
					Long agentMemberId =  MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), edocRegister.getDistributerId()); 
					if(agentMemberId != null){
						//distributeAffair(subject, registerUserId, agentMemberId, edocRegister.getId(), edocRegister.getDistributeEdocId(), "create");
						sendRegisterMessage(key , subject, registerName, agentToName, userId, registerId, agentMemberId, "col.agent", "", url, linkOpenType, registerId, agentApp);
					}				
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
    
    private void distributeAffair(String subject, long senderId, long memberId, Long objectId, Long subObjectId, String comm,String...bodyType) {
    	Affair reAffair = null;
    	if(comm.equals("delete")) {
    		affairManager.deleteByObject(ApplicationCategoryEnum.edocRegister, objectId);
    	} else if(comm.equals("create")) {//这里注意，登记ojbectId, subState  分发：subObjectId, state
    		reAffair = new Affair();
    		reAffair.setIdIfNew();
    		reAffair.setSubject(subject);
    		reAffair.setMemberId(memberId);
    		reAffair.setSenderId(senderId);    		
    		reAffair.setCreateDate(new Timestamp(System.currentTimeMillis()));
    		reAffair.setObjectId(objectId);//登记的id
    		reAffair.setSubObjectId(subObjectId);//分发的id
    		// wangjingjing begin 发文分发 等于 交换中心的 待发送，所以这里的分发一定是 收文分发
    		reAffair.setApp(ApplicationCategoryEnum.edocRecDistribute.getKey());
    		//reAffair.setApp(31);
    		// wangjingjing end
        	reAffair.setState(3);//分发的状态
        	
        	//-------------待分发列表没有显示word图标bug 修复  changyi add
        	if(bodyType !=null && bodyType.length == 1)
        		reAffair.setBodyType(bodyType[0]);
    		affairManager.addAffair(reAffair);
    	}
    }
    
    /**
     * 
     * @param key 消息内容
     * @param subject 消息内容参数1：主题
     * @param userName 消息内容参数2：登记人
     * @param agentName 消息代登记参数1：代理登记人
     * @param fromUserId 由谁发起
     * @param registerId 登记id
     * @param toUserId 发给谁
     * @param colAgent (代理)接收者是否为代理
     * @param agentDeal (由..处理) 代理处理消息
     * @param url 链接url
     * @param linkType 打开消息类型
     * @param param 消息内容 参数
     * @param agentApp 代理参数标识 发给代理人：app=agent
     * @throws Exception 
     */
    private void sendRegisterMessage(String key, String subject, String userName, String agentName, long fromUserId, long registerId, long toUserId, String colAgent, String agentDeal, String url, com.seeyon.v3x.common.usermessage.Constants.LinkOpenType linkType, long param, String agentApp) throws Exception { 
		MessageReceiver receiver = new MessageReceiver(registerId, toUserId, url, linkType, EdocEnum.edocType.recEdoc.ordinal(), param, agentApp);
		MessageContent messageContent = new MessageContent(key, subject, userName);
		messageContent.add(colAgent);
		messageContent.add(agentDeal, agentName);
		userMessageManager.sendSystemMessage(messageContent, ApplicationCategoryEnum.edocRecDistribute, fromUserId, receiver);
    }
    
    /** 保存登记单 -唐桂林2011-10-12 */
    public ModelAndView deleteRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	String listType = request.getParameter("listType");
    	String edocType = request.getParameter("edocType");
    	String[] ids = request.getParameterValues("registerId");
    	String[] registerTypes = request.getParameterValues("registerType");
    	if(registerTypes!=null) { 
    		RegisterBody registerBody = null;
    		List<EdocRegister> registerList = edocRegisterManager.findList(ids);
    		if(registerList != null) {
    			for(EdocRegister edocRegister : registerList) {
    				if(edocRegister.getRegisterType()==2 && edocRegister.getState()==0) {//草稿箱中的手工登记则全删
    					attachmentManager.deleteByReference(edocRegister.getId());
    					registerBody = edocRegisterManager.findRegisterBodyByRegisterId(edocRegister.getId());
    					if(registerBody!=null) {
    						registerBody.setEdocRegister(edocRegister);
    						edocRegister.setRegisterBody(registerBody);
    					}
    					edocRegisterManager.deleteEdocRegister(edocRegister);
    				} else {//自动登记，已登记的纸质登记 物理删除
    					edocRegisterManager.updateEdocRegisterState(edocRegister.getId(), EdocNavigationEnum.RegisterState.deleted.ordinal());
    				}
    			}
    		}
    	}
    	return super.redirectModelAndView("/edocController.do?method=listRegister&listType="+listType+"&from=listRegister&edocType="+edocType);
    }
    
    /** 保存登记单 -唐桂林2011-10-12 */
    public ModelAndView cancelRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	String listType = request.getParameter("listType");
    	String edocType = request.getParameter("edocType");
    	String[] ids = request.getParameterValues("registerId");
    	String[] registerTypes = request.getParameterValues("registerType");
    	if(registerTypes!=null) { 
    		List<EdocRegister> registerList = edocRegisterManager.findList(ids);
    		if(registerList != null) {
    			List<EdocRegister> list = new ArrayList<EdocRegister>();
    			for(EdocRegister edocRegister : registerList) {
    				if(edocRegister.getRegisterType()!=1 && edocRegister.getRecieveId()==-1) {//纸质/二维码登记公文允许撤销
    					edocRegister.setState(EdocNavigationEnum.RegisterState.DraftBox.ordinal());
        				edocRegister.setIsRetreat(0);
        				list.add(edocRegister);
        				
        				Map<String, Object> columns = new HashMap<String, Object>();
                		columns.put("isDelete", true);
        				Object[][] wheres = new Object[3][2];
                		wheres[0] = new Object[]{"app", ApplicationCategoryEnum.edocRegister.key()};
                		wheres[1] = new Object[]{"objectId", edocRegister.getId()};
                		wheres[2] = new Object[]{"state", StateEnum.col_pending.getKey()};
                		
                		affairManager.update(columns, wheres);
    				}
    			}
    			edocRegisterManager.updateEdocRegister(list);
    		}
    	}
    	return super.redirectModelAndView("/edocController.do?method=listRegister&listType="+listType+"&from=listRegister&edocType="+edocType);
    }    
    
	/**
	 * 
	 * @param createPersionName
	 * @param summary
	 * @param orgAccountId
	 * @param contentNo 收文记录接受到的正文的编号。
	 * @return
	 * @throws CloneNotSupportedException
	 */
	private EdocSummary cloneNewSummaryAndSetProperties(String createPersionName, EdocSummary summary, Long orgAccountId,Integer contentNo) throws CloneNotSupportedException {
		EdocSummary edocSummary = null;
		if(summary != null){
			edocSummary= (EdocSummary)summary.clone();
			edocSummary.setCreatePerson(createPersionName); 
			edocSummary.setDeadline(0L);
			edocSummary.setAdvanceRemind(0L);
			edocSummary.setOrgAccountId(orgAccountId);
			edocSummary.setSerialNo(null);
			edocSummary.setArchiveId(null);
			//传入的参数ContentnO可能为空，所以进行防护性处理，先取出一个EdocBody.
			EdocBody eb = edocSummary.getFirstBody();
			for(EdocBody ebody :edocSummary.getEdocBodies()){
				if(ebody.getContentNo().equals(contentNo)){ 
					eb = ebody;
					break;
				}
			}
			edocSummary.setEdocBodies(new HashSet<EdocBody>());
			edocSummary.getEdocBodies().add(eb);
			//登记时候,为了保证印章校验有效,必须保持原来的文件名称不变(office控件的FileName属性一致才可以)
			if(!com.seeyon.v3x.common.constants.Constants.EDITOR_TYPE_HTML.equals(summary.getFirstBody().getContentType()))
			{
				edocSummary.getFirstBody().setContentName(summary.getFirstBody().getContent());
			}
		}
		if(edocSummary == null){
			edocSummary = new EdocSummary();
		}
		return edocSummary;
	}
	private List<Attachment> excludeType2ToNewAttachmentList(EdocSummary summary) {
		List<Attachment> exclude2List=new ArrayList<Attachment>();//需要重新new一个List，不能在atts的基础上使用remove.
		
		//-----------------解决收文转发文时的bug,summary有可能为null
		if(summary != null){
			List<Attachment> atts= attachmentManager.getByReference(summary.getId(), summary.getId());
			
			for(Attachment att:atts){
				if(!Integer.valueOf(2).equals(att.getType()))
					exclude2List.add(att);
			}
		}
		return exclude2List;
	}
    /**
    * 查找签收部门所属单位或者签收单位
    * @param exchangeId   EdocRecieveRecord的ID
    * @return
    */
   private Long getAccountIdOfRegisterByExchangeId(Long exchangeId){
		EdocRecieveRecord record = recieveEdocManager.getEdocRecieveRecord(Long.valueOf(exchangeId));
		return getAccountIdOfRegisterByOrgIdAndOrgType(record.getExchangeOrgId(),record.getExchangeType());
   }
   /**
    * 查找签收部门所属单位或者签收单位
    * @param exchangeOrgId 签收ID（单位ID|部门ID）
    * @param exchangeOrgType  签收类型（部门|单位）
    * @return
    */
   private Long getAccountIdOfRegisterByOrgIdAndOrgType(Long exchangeOrgId,int exchangeOrgType){
   	if(com.seeyon.v3x.exchange.util.Constants.C_iAccountType_Dept==exchangeOrgType){
			V3xOrgDepartment dept;
			try {
				dept = orgManager.getDepartmentById(exchangeOrgId);
				return dept.getOrgAccountId();
			} catch (BusinessException e) {
				log.error("查找部门异常:",e);
			}
		}else {
			return exchangeOrgId;	
		}
   	return 0L;
   }
   /**
    * 取得指定【单位，公文单类型】或者【指定模板公文单】的公文单列表。
    * 非流程模板，只取模板公文单，流程模板和自由流程取所有公文单。
    * @param accountId ：特定单位
    * @param iEdocType ：公文单类型
    * @param formId    ：公文单ID
    * @param templeteTypeName:模板类型，流程模板，格式模板
    * @return
    */
   private List<EdocForm>  getLoginAccountOrCurrentTempleteEdocForms(long accountId,String domainIds,int iEdocType,String templeteId,long formId,String templeteTypeName, long subType){
	List<EdocForm> edocForms =new ArrayList<EdocForm>();
   	if(Strings.isNotBlank(templeteId) && !Templete.Type.workflow.name().equals(templeteTypeName)){
   		EdocForm ef=edocFormManager.getEdocForm(formId);
   		edocForms.add(ef);
   	}else {
   		edocForms=edocFormManager.getEdocForms(accountId,domainIds,iEdocType, subType); 
   		
   		//过滤掉兼职重复的公文单
   		List<EdocForm> l = new ArrayList<EdocForm>();
   		Set<Long> filter = new HashSet<Long>();
   		for(EdocForm form : edocForms){
   			if(!filter.contains(form.getId())) {
   				filter.add(form.getId());
   				l.add(form);
   			}
   		}
   		edocForms = l;
   	}
   	//去掉停用的
   	for(Iterator<EdocForm> it = edocForms.iterator();it.hasNext();){
   		EdocForm ef = it.next();
   		if(ef.getStatus()!= null && ef.getStatus().intValue() != EdocForm.C_iStatus_Published.intValue())
   			it.remove();
   	}
   	return edocForms;
   }

    /**
     * 发公文前的检查
     * 当发送公文是通过模板的，必须先走这一步，设置可能的选人信息（ProcessModeSelector)
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @deprecated 使用collaboration.preSend方法代替。
     */
   @Deprecated
    public ModelAndView preSend(HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
    	if(Strings.isBlank(request.getParameter("__ActionToken"))){
    		PrintWriter out = response.getWriter();
    		out.println("<script>alert('操作失败：网络异常，系统无法获取所需的提交数据。');</script>");
    		return null;
    	}
  	
        FlowData flowData = FlowData.flowdataFromRequest();
        String currentNodeId = request.getParameter("currentNodeId");
        String isFromTemplate = request.getParameter("isFromTemplate");
        ModelAndView mav = new ModelAndView("collaboration/processModeSelectorMain");
        String processId = null;
        
        String splitProcessId = request.getParameter("processId");
        String _affairId = request.getParameter("affair_id");        
        //      是否是督办时的匹配节点
        String fromColsupervise = request.getParameter("fromColsupervise");
        mav.addObject("fromColsupervise", fromColsupervise);
        Boolean excuteFlag = true;
        Affair affair = null;
        if(_affairId != null && !"".equals(_affairId)){
	        affair = affairManager.getById(Long.parseLong(_affairId));
	        if(affair.getState() != StateEnum.col_pending.key()){
	        	excuteFlag = false;
	        }
        }
        
        if(excuteFlag){
        	BPMProcess process = null;
        	if(!flowData.isEmpty()) {
		        if(flowData.getXml() == null){
			        //根据选人界面传来的people生成流程模板XML
			        processId = EdocHelper.saveOrUpdateProcessByFlowData(flowData, processId, false);
			        //生成流程模板对象
			        process = EdocHelper.getProcess(processId);
			        EdocHelper.deleteReadyProcess(processId);
			        String caseProcessXML = process.toXML();
			        if(StringUtils.isNotBlank(caseProcessXML)){
			        	caseProcessXML = EdocHelper.trimXMLProcessor(caseProcessXML);
						flowData.setXml(caseProcessXML);
			        }
			        currentNodeId = process.getStart().getId();
			        mav.addObject("caseProcessXML", StringEscapeUtils.escapeHtml(caseProcessXML));
			        mav.addObject("process_desc_by", FlowData.DESC_BY_XML);
		        }else {
		        	process = flowData.toBPMProcess();
		        }
        	}else {
        		processId = request.getParameter("processId");
        		process = EdocHelper.getCaseProcess(processId);
        	}
        	
        	if(Strings.isNotBlank(currentNodeId) && !"start".equals(currentNodeId)){
        		BPMSeeyonPolicy seeyonPolicy = process.getActivityById(currentNodeId).getSeeyonPolicy();
        		if(!EdocHelper.isExecuteFinished(process, affair) || "zhihui".equals(seeyonPolicy.getId())) {
        			return mav;
        		}
        	}
	        boolean templateFlag = new Boolean(isFromTemplate).booleanValue();
	        
	        long caseId = 0;
			String _caseId = request.getParameter("caseId");
			if(Strings.isNotBlank(_caseId)){
				caseId = Long.parseLong(_caseId);
			}
			
			if(!"start".equals(currentNodeId) && caseId == 0){ //发起时，case不存在
				log.warn("=======================================\\n处理公文时，caseId不存在。Parameter：" + request.getParameterMap() + "\\n=======================================");
			}
			
	        WorkflowEventListener.ProcessModeSelector selector = EdocHelper.preRunCase(process,currentNodeId, templateFlag, caseId);
	        List<NodeAddition> invalidateActivity = selector.getInvalidateActivity();
	        if(invalidateActivity != null && !invalidateActivity.isEmpty()){ //存在不可用的节点，不让发
	        	mav.addObject("invalidateActivity", invalidateActivity);
	        	return mav;
	        }
	        
	        //key 节点id
	        Map<String, ProcessModeSelectorModel> selectorModels = new LinkedHashMap<String, ProcessModeSelectorModel>();
	        List<String> selectorModelNodeIds = new ArrayList<String>();
            if(selector != null){
                List<NodeAddition> nodeAdditions = selector.getNodeAdditions();
                if(nodeAdditions != null){
                    for(int m=nodeAdditions.size()-1;m>=0;m--){
                    	NodeAddition addition=nodeAdditions.get(m);
                    	ProcessModeSelectorModel selectorModel = new ProcessModeSelectorModel();
                    	selectorModel.setAddition(addition);
                    	selectorModel.setNodeId(addition.getNodeId());
                    	selectorModel.setNodeName(addition.getNodeName());
                    	
                    	selectorModels.put(addition.getNodeId(), selectorModel);
                    	selectorModelNodeIds.add(addition.getNodeId());
                    }
                }
            }
	
	        HashMap<String,String> hash = new HashMap<String,String>(); 
	        if("start".equals(currentNodeId)) {
	        	hash.put("currentIsStart", "true");
	        	ColHelper.findDirectHumenChildrenCondition(process.getStart(), hash);
	        }
	        else
	        	ColHelper.findDirectHumenChildrenCondition(process.getActivityById(currentNodeId), hash);
	        if(hash.size()>0){
	        	//发起人信息
	        	V3xOrgMember member = null;
	        	V3xOrgPost standardPost = null;
	        	V3xOrgLevel groupLevel = null;
	        	long startDepartment = -1;
	        	long startPost = -1;
	        	long startLevel = -1;
	        	long startAccount = -1;
	        	long startStandardPost = -1;
	        	long startGroupLevel = -1;
	        	long startId = -1;
	        	if(!"start".equals(currentNodeId)) {
		        	EdocSummary summary = null;
		        	if(affair != null)
		        	   summary = edocManager.getEdocSummaryById(affair.getObjectId(), false);
		        	if(summary == null){
		        		if(processId != null){
		        			summary = edocManager.getSummaryByProcessId(processId);
		        		}else{
		        			summary = edocManager.getSummaryByProcessId(splitProcessId);
		        		}
		        	}
		        	member = orgManager.getMemberById(summary.getStartUserId());
		        	startId = member.getId();
		        	startDepartment = member.getOrgDepartmentId();
		        	startPost = member.getOrgPostId();
		        	startLevel = member.getOrgLevelId();
		        	startAccount = member.getOrgAccountId();
		        	standardPost = this.orgManager.getBMPostByPostId(startPost);
		        	groupLevel = this.orgManager.getLevelById(startLevel);
		        	if(standardPost != null)
		        		startStandardPost = standardPost.getId();
		        	if(groupLevel != null && groupLevel.getGroupLevelId() != null)
		        		startGroupLevel = groupLevel.getGroupLevelId();
	        	}
	        	
	        	Set<Map.Entry<String, String>> entry = hash.entrySet();
	        	List<String> keys = new ArrayList<String>();
	        	List<String> nodeNames = new ArrayList<String>();
	        	List<String> conditions = new ArrayList<String>();
	        	List<String> forces = new ArrayList<String>();
	        	List<String> links = new ArrayList<String>();
	        	List<Integer> conditionTypes = new ArrayList<Integer>();
	        	String[] temp = null;
	        	String[] temp1 = null;
	        	String order = hash.get("order");
	        	if(order != null && order.indexOf("$")!=-1) {
	        		temp1 = StringUtils.split(order,"$");
	        	}
	        	if("start".equals(currentNodeId))
	        		member = orgManager.getMemberById(CurrentUser.get().getId());
	        	else
	        		//兼容代理的情况，直接取当前affair的memberid
	        		member = orgManager.getMemberById(affair.getMemberId());
	        	standardPost = this.orgManager.getBMPostByPostId(member.getOrgPostId());
	        	groupLevel = this.orgManager.getLevelById(member.getOrgLevelId());
	        	StringBuffer sb = new StringBuffer();
	        	if(temp1!=null && temp1.length>0) {
	        		for(String item:temp1){
	        			String value = hash.get(item);
	            		if(value!=null&&value.indexOf("↗")!=-1){
	            			sb.append(item+":");
	    	        		keys.add(item);
	    	        		links.add(hash.get("linkTo"+item));    	        		
	    	        		temp = value.split("↗");
	    	        		if(temp != null){
	    	        			nodeNames.add(temp[0]);
	    	        			if(temp[1].indexOf("ispost")!=-1 || temp[1].indexOf("isNotpost")!=-1 || temp[1].indexOf("isStartpost")!=-1 || temp[1].indexOf("isNotStartpost")!=-1){
	    	        				temp[1] = EdocHelper.calcExpression(startId, CurrentUser.get().getId(), this.orgManager, temp[1]);
	    	        			}
	    	        			temp[1] = temp[1].replaceAll("Department", String.valueOf(member.getOrgDepartmentId()))
	    	        			.replaceAll("Post",String.valueOf(member.getOrgPostId())).replaceAll("Level", String.valueOf(member.getOrgLevelId()))
	    	        			.replaceAll("Account", String.valueOf(member.getOrgAccountId())).replaceAll("standardpost", (standardPost==null?"-1":standardPost.getId().toString()))
	    	        			.replaceAll("grouplevel", groupLevel==null||groupLevel.getGroupLevelId()==null?"-1":groupLevel.getGroupLevelId().toString())
	    	        			.replaceAll("'", "\\\\\'").replaceAll("&#91;", "").replaceAll("&#93;", "");
	    	        			if(temp[1].indexOf("handCondition")!=-1) {
	    	        				temp[1] = temp[1].replaceAll("handCondition","false");
	    	        				conditionTypes.add(2);
	    	        			}else
	    	        				conditionTypes.add(0);
	    	        			if(!"start".equals(currentNodeId))    	        				
	    	        				temp[1] = temp[1].replaceAll("startdepartment", String.valueOf(startDepartment)).replaceAll("startpost",String.valueOf(startPost))
	    	        				.replaceAll("startlevel", String.valueOf(startLevel)).replaceAll("startaccount", String.valueOf(startAccount))
	    	        				.replaceAll("startStandardpost", String.valueOf(startStandardPost)).replaceAll("startGrouplevel", String.valueOf(startGroupLevel))
	    	        				.replaceAll("&#91;", "").replaceAll("&#93;", "");
	    	        			conditions.add(temp[1]);
	    	        			if(temp.length==3 && "1".equals(temp[2]))
	    	        				forces.add("true");
	    	        			else
	    	        				forces.add("false");
	    	        		}
	            		}
	            	}
	        	}else {
		        	for(Map.Entry<String, String> item:entry){
		        		if(item.getValue()!=null&&item.getValue().indexOf("↗")!=-1){
		        			sb.append(item.getKey()+":");
			        		keys.add(item.getKey());
			        		links.add(hash.get("linkTo"+item.getKey()));
			        		temp = item.getValue().split("↗");
			        		if(temp != null){
			        			nodeNames.add(temp[0]);
			        			if(temp[1].indexOf("ispost")!=-1 || temp[1].indexOf("isNotpost")!=-1 || temp[1].indexOf("isStartpost")!=-1 || temp[1].indexOf("isNotStartpost")!=-1){
	    	        				temp[1] = EdocHelper.calcExpression(startId, CurrentUser.get().getId(), this.orgManager, temp[1]);
	    	        			}
			        			temp[1] = temp[1].replaceAll("Department", String.valueOf(member.getOrgDepartmentId()))
			        			.replaceAll("Post",String.valueOf(member.getOrgPostId())).replaceAll("Level", String.valueOf(member.getOrgLevelId()))
			        			.replaceAll("Account", String.valueOf(member.getOrgAccountId())).replaceAll("standardpost", (standardPost==null?"-1":standardPost.getId().toString()))
			        			.replaceAll("grouplevel", groupLevel==null||groupLevel.getGroupLevelId()==null?"-1":groupLevel.getGroupLevelId().toString())
			        			.replaceAll("'", "\\\\\'").replaceAll("&#91;", "").replaceAll("&#93;", "");
			        			if(temp[1].indexOf("handCondition")!=-1) {
	    	        				temp[1] = temp[1].replaceAll("handCondition","false");
	    	        				conditionTypes.add(2);
	    	        			}else
	    	        				conditionTypes.add(0);
			        			if(!"start".equals(currentNodeId))		        				
			        				temp[1] = temp[1].replaceAll("startdepartment", String.valueOf(startDepartment))
			        				.replaceAll("startpost",String.valueOf(startPost)).replaceAll("startlevel", String.valueOf(startLevel))
			        				.replaceAll("startaccount", String.valueOf(startAccount))
			        				.replaceAll("startStandardpost", String.valueOf(startStandardPost)).replaceAll("startGrouplevel", String.valueOf(startGroupLevel))
			        				.replaceAll("&#91;", "").replaceAll("&#93;", "");
			        			conditions.add(temp[1]);
			        			if(temp.length==3)
			        				forces.add("true");
			        			else
			        				forces.add("false");
			        		}
		        		}
		        	}
	        	}
	        	
	        	if(keys.size() > 0 && conditions.size() > 0){
		        	mav.addObject("allNodes", sb.toString());
		        	mav.addObject("nodeCount", hash.get("nodeCount"));
		        	
		        	for (int k = keys.size()-1; k >=0; k--) {
		        		String nodeId = keys.get(k);
		        		ProcessModeSelectorModel selectorModel = selectorModels.get(nodeId);
		        		if(selectorModel == null){
		        			selectorModel = new ProcessModeSelectorModel();
		        			
		        			selectorModels.put(nodeId, selectorModel);
		        			selectorModelNodeIds.add(nodeId);
		        			selectorModel.setProcessMode(process.getActivityById(nodeId).getProcessMode());
		        		}
		        		selectorModel.setNodeId(nodeId);
		        		selectorModel.setNodeName(nodeNames.get(k));
		        		selectorModel.setCondition(conditions.get(k));
		        		selectorModel.setForce(forces.get(k));
		        		selectorModel.setLink(links.get(k));
		        		selectorModel.setConditionType(conditionTypes.get(k));
					}
		        }
	        }
	        
	        mav.addObject("selectorModels", selectorModels);
	        mav.addObject("selectorModelNodeIds", selectorModels.keySet());
        }
        else{
        	mav.addObject("selectorModels",null);
        }
        
        return mav;
    }
    
    /**
     * 意见回复
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView doComment(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
    	Long summaryId = new Long(request.getParameter("summaryId"));
    	EdocSummary edocSummary=edocManager.getEdocSummaryById(summaryId,false);
    	
    	//是否发送消息
    	boolean isSendMessage = request.getParameterValues("isSendMessage") != null;
    	Timestamp now = new Timestamp(System.currentTimeMillis());
    	
    	//发起人增加附言
    		
        EdocOpinion senderOpinion = new EdocOpinion();
        senderOpinion.setIdIfNew();

        senderOpinion.setCreateTime(now);
        senderOpinion.setContent(request.getParameter("postscriptContent"));
        senderOpinion.setCreateUserId(user.getId());
        senderOpinion.setOpinionType(EdocOpinion.OpinionType.senderOpinion.ordinal());
        senderOpinion.setEdocSummary(edocSummary);
        senderOpinion.setIsHidden(false);

        this.edocManager.saveOpinion(senderOpinion, isSendMessage);
            
        this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, senderOpinion.getId(), request);
    	
    	super.rendJavaScript(response, "parent.replyCommentOK('" + Datetimes.formateToLocaleDatetime(now) + "')");
    	return null;
    }
    
    public ModelAndView waitSendPreSend(HttpServletRequest request,HttpServletResponse response) throws Exception 
    {
    	ModelAndView mav = new ModelAndView("collaboration/processModeSelectorMain");
    	String _summaryId = request.getParameter("summaryId");
    	Long summaryId = Long.parseLong(_summaryId);
    	EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
    	String processId = summary.getProcessId();
    	if(processId==null || "".equals(processId))
    	{
    		response.getWriter().println("err:noflow");    		
    		return null;
    	}
    	
    	BPMProcess process = ColHelper.getRunningProcessByProcessId(processId);
    	if(process == null){
    		response.getWriter().println("err:noflow");    		
    		return null;
    	}
    	/*
    	//检查是否有主送单位
    	if(summary.getEdocType()==EdocEnum.edocType.sendEdoc.ordinal() && (summary.getSendToId()==null || "".equals(summary.getSendToId())))
		{
    		response.getWriter().println("err:noMainSendComp");    		
    		return null;
		}
		*/
    	Long templateId = summary.getTempleteId();
    	boolean templateFlag = false;
    	if(templateId != null) templateFlag = true;

		long caseId = 0;
		String _caseId = request.getParameter("caseId");
		if(Strings.isNotBlank(_caseId)){
			caseId = Long.parseLong(_caseId);
		}

    	WorkflowEventListener.ProcessModeSelector selector = EdocHelper.preRunCase(process, "start", templateFlag, caseId);
        List<NodeAddition> invalidateActivity = selector.getInvalidateActivity();
        if(invalidateActivity != null && !invalidateActivity.isEmpty()){ //存在不可用的节点，不让发
        	mav.addObject("invalidateActivity", invalidateActivity);
        	return mav;
        }
        
    	//分枝 开始
    	
		HashMap<String,String> hash = new HashMap<String,String>(); 
		hash.put("currentIsStart", "true");
        ColHelper.findDirectHumenChildrenCondition(process.getStart(), hash);
        if(hash.size()>0){
        	Set<Map.Entry<String, String>> entry = hash.entrySet();
        	List<String> keys = new ArrayList<String>();
        	List<String> nodeNames = new ArrayList<String>();
        	List<String> conditions = new ArrayList<String>();
        	List<String> forces = new ArrayList<String>();
        	List<String> links = new ArrayList<String>();
        	List<Integer> conditionTypes = new ArrayList<Integer>();
        	String[] temp = null;
        	String[] temp1 = null;
        	String order = hash.get("order");
        	if(order != null && order.indexOf("$")!=-1) {
        		temp1 = StringUtils.split(order,"$");
        	}
        	User user = CurrentUser.get();
        	StringBuffer sb = new StringBuffer();
        	if(temp1!=null && temp1.length>0) {
        		for(String item:temp1){
        			String value = hash.get(item);
            		if(value!=null&&value.indexOf("↗")!=-1){
            			sb.append(item+":");
    	        		keys.add(item);
    	        		links.add(hash.get("linkTo"+item));
    	        		temp = value.split("↗");
    	        		if(temp != null){
    	        			nodeNames.add(temp[0]);
    	        			temp[1] = temp[1].replaceAll("Department", String.valueOf(user.getDepartmentId())).replaceAll("Post",String.valueOf(user.getPostId())).replaceAll("Level", String.valueOf(user.getLevelId())).replaceAll("Account", String.valueOf(user.getAccountId())).replaceAll("'", "\\\\\'").replaceAll("&#91;", "").replaceAll("&#93;", "");
    	        			if(temp[1].indexOf("handCondition")!=-1) {
    	        				temp[1] = temp[1].replaceAll("handCondition","false");
    	        				conditionTypes.add(2);
    	        			}else
    	        				conditionTypes.add(0);
    	        			conditions.add(temp[1]);
    	        			if(temp.length==3 && "1".equals(temp[2]))
    	        				forces.add("true");
    	        			else
    	        				forces.add("false");
    	        		}
            		}
            	}
        	}else {
	        	for(Map.Entry<String, String> item:entry){
	        		if(item.getValue()!=null&&item.getValue().indexOf("↗")!=-1){
	        			sb.append(item.getKey()+":");
		        		keys.add(item.getKey());
		        		links.add(hash.get("linkTo"+item.getKey()));
		        		temp = item.getValue().split("↗");
		        		if(temp != null){
		        			nodeNames.add(temp[0]);
		        			temp[1] = temp[1].replaceAll("Department", String.valueOf(user.getDepartmentId())).replaceAll("Post",String.valueOf(user.getPostId())).replaceAll("Level", String.valueOf(user.getLevelId())).replaceAll("Account", String.valueOf(user.getAccountId())).replaceAll("'", "\\\\\'").replaceAll("&#91;", "").replaceAll("&#93;", "");
		        			if(temp[1].indexOf("handCondition")!=-1) {
    	        				temp[1] = temp[1].replaceAll("handCondition","false");
    	        				conditionTypes.add(2);
    	        			}else
    	        				conditionTypes.add(0);
		        			conditions.add(temp[1]);
		        			if(temp.length==3)
    	        				forces.add("true");
    	        			else
    	        				forces.add("false");
		        		}
	        		}
	        	}
        	}
        	if(keys.size() > 0 && conditions.size() >0){
	        	mav.addObject("allNodes", sb.toString());
	        	mav.addObject("keys", keys);
	        	mav.addObject("names", nodeNames);
	        	mav.addObject("conditions", conditions);
	        	mav.addObject("nodeCount", hash.get("nodeCount"));
	        	mav.addObject("forces", forces);
	        	mav.addObject("links", links);
	        	mav.addObject("templateId", templateId);
	        }
        }
    	//分枝 结束    	

    	mav.addObject("processModeSelector",selector);

    	return mav;
    }
    /**
     * 登记使用的文号,返回真正的文号串
     * @param markStr:掩码格式文号，详细见EdocMarkModel.parse()方法
     * @param markNum
     */
    private String registDocMark(Long summaryId,String markStr,int markNum,int edocType,boolean checkId,int markType) throws EdocMarkHistoryExistException
    {
        EdocMarkModel em=EdocMarkModel.parse(markStr);
        if (em!=null)
        {
        	Integer t = em.getDocMarkCreateMode();//0:未选择文号，1：下拉选择的文号，2：选择的断号，3.手工输入
        	String _edocMark = em.getMark(); //需要保存到数据库中的公文文号      
        	Long markDefinitionId = em.getMarkDefinitionId();
        	Long edocMarkId = em.getMarkId();
        	User user = CurrentUser.get();
	        if(markType==EdocEnum.MarkType.edocMark.ordinal()){//公文文号
	        	if(t!=0){//等于0的时候没有进行公文文号修改
	        		edocMarkManager.disconnectionEdocSummary(summaryId,markNum);
	        	}
	        	if(edocType != com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_SIGN) {
	        		if (t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_NEW) { // 选择了一个新的公文文号
	        			Integer currentNo = em.getCurrentNo();
	        			edocMarkManager.createMark(markDefinitionId, currentNo, _edocMark, summaryId,markNum);
	        		}
	        		else if (t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_OLD) { // 选择了一个断号
	        			edocMarkManager.createMarkByChooseNo(edocMarkId, summaryId,markNum);
	        		}
	        		else if (t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_INPUT) { // 手工输入一个公文文号
	        			edocMarkManager.createMark(_edocMark, summaryId,markNum);
	        		}
	        	}else {//签报处理
	        		if (t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_NEW) {
	        			this.edocMarkHistoryManager.save(summaryId,_edocMark,markDefinitionId,markNum,user.getId(),user.getId(),checkId,true);
	        		}else if(t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_OLD) {
	        			this.edocMarkHistoryManager.saveMarkHistorySelectOld(edocMarkId,_edocMark,summaryId, user.getId(),checkId);
	        		}else if(t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_INPUT) {
	        			this.edocMarkHistoryManager.save(summaryId,_edocMark,markDefinitionId,markNum,user.getId(),user.getId(),checkId,false);
	        		}
	        	}
	        }else if(markType==EdocEnum.MarkType.edocInMark.ordinal()){//内部文号
	        	if(t == com.seeyon.v3x.edoc.util.Constants.EDOC_MARK_EDIT_SELECT_NEW){
	        		this.edocMarkDefinitionManager.setEdocMarkCategoryIncrement(markDefinitionId);
	        	}
	        }
	        return _edocMark;
        }    	
    	return null;
    }
    
    /**
     * 发送公文,跳转到已�发
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView send(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	//cy add 从收文页面传递 登记表edoc_register的标识id
    	String edocRegisterId = request.getParameter("edocRegisterId");
    	String allNodes = request.getParameter("allNodes");  
    	String branchNodes = request.getParameter("branchNodes");
    	//json格式的字符串:选人
    	String popNodeSelected = request.getParameter("popNodeSelected");
    	//json格式的字符串:条件分支
    	String popNodeCondition = request.getParameter("popNodeCondition");
    	//json格式的字符串:新流程信息
    	String popNodeNewFlow = request.getParameter("popNodeNewFlow");
    	// lijl获取处理类型的值-----------------------------------------------Start
		String processTypeStr = request.getParameter("processType");
		Long processType = 0L;
		if (processTypeStr != null && !"".equals(processTypeStr)) {
			processType = Long.parseLong(processTypeStr);
		}
		// lijl获取处理类型的值-----------------------------------------------End
    	if(log.isInfoEnabled()){
    		log.info("popNodeSelected:="+popNodeSelected);
        	log.info("popNodeCondition:="+popNodeCondition);
        	log.info("popNodeNewFlow:="+popNodeNewFlow);
    	}   
    	boolean lostBranchData = branchNodes != null && !branchNodes.equals(allNodes);
    	if(Strings.isBlank(request.getParameter("__ActionToken")) || lostBranchData){
    		if(lostBranchData)
    			log.error("不能获取分支数据，allNodes:"+allNodes+" branchNodes:"+branchNodes);
    		PrintWriter out = response.getWriter();
    		out.println("<script>alert('操作失败：网络异常，系统无法获取所需的提交数据。');");
    		out.println("history.back();</script>");
    		return null;
    	}
    	/**
    	 * 表单ID
    	 */
    	long formId=Long.parseLong(request.getParameter("edoctable"));
       
    	
    	//检查公文单是否已经被删除。“当前公文单不存在，可能已经被删除，请检查。”
    	boolean isExsit = edocFormManager.isExsit(formId);
        if(!isExsit){
        	PrintWriter out = response.getWriter();
        	String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_edocform_isnotexsit");
    		out.println("<script>alert('"+errMsg+"');");
    		out.println("history.back();</script>");
    		return null;
        }  
           
        
    	User user = CurrentUser.get();
    	String comm=request.getParameter("comm");

		boolean isCanBeRegisted = true;
		// 来文登记,更新登记时间，给签收人发送消息
		long registerId = Strings.isBlank(request.getParameter("registerId"))?-1:Long.parseLong(request.getParameter("registerId"));
		Long agentId = null;
		Long agentToId = null;
		EdocRegister edocRegister = null;
		if ("distribute".equals(comm) && registerId!=-1) {
			edocRegister = edocRegisterManager.findRegisterById(registerId);
			if(edocRegister != null) {
				
				// 登记公文，判断当前操作人是否可以登记此公文
				Long recordRegisterUserId = edocRegister.getDistributerId();
			
				boolean isNotAgent = false;
				agentId = MemberAgentBean.getInstance().getAgentMemberId(ApplicationCategoryEnum.edoc.key(), recordRegisterUserId);
				if(agentId != null) {
					if(!Long.valueOf(user.getId()).equals(agentId)){
						isNotAgent = true;
					}
				}		
				if (recordRegisterUserId.longValue() != user.getId() && isNotAgent) {
					// 公文登记人已经转换
					isCanBeRegisted = false;
					String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasChanged_distribute");
					PrintWriter out = response.getWriter();
					// super.printV3XJS(out);
					out.println("<script>");
					out.println("alert(\"" + errMsg + "\")");
					out.println("if(window.dialogArguments){"); // 弹出
					out.println("  window.returnValue = \"true\";");
					out.println("  window.close();");
					out.println("}else{");
					if("agent".equals(request.getParameter("app"))) {
						out.println("	parent.parent.location.href='main.do?method=morePending4App&app=agent';");
					} else {
						out.println("	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType=1';");
					}
					out.println("}");
					out.println("");
					out.println("</script>");
					return null;
				}
				if (edocRegister.getIsRetreat() == 1) {
					// 公文已经回退
					isCanBeRegisted = false;
					String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasBeStepBack_already");
					PrintWriter out = response.getWriter();
					// super.printV3XJS(out);
					out.println("<script>");
					out.println("alert(\"" + errMsg + "\")");
					out.println("if(window.dialogArguments){"); // 弹出
					out.println("  window.returnValue = \"true\";");
					out.println("  window.close();");
					out.println("}else{");
					if("agent".equals(request.getParameter("app"))) {
						out.println("	parent.parent.location.href='main.do?method=morePending4App&app=agent';");
					} else {
						out.println("	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType=1';");
					}
					out.println("}");
					out.println("");
					out.println("</script>");
					return null;
				}
				if (edocRegister.getDistributeState() == EdocNavigationEnum.EdocDistributeState.Distributed.ordinal()) {// 公文已经分发
					isCanBeRegisted = false;
					ModelAndView modelAndView = new ModelAndView("common/redirect");
					String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_has_registe");
					modelAndView.addObject("redirectURL", BaseController.REDIRECT_BACK);
					modelAndView.addObject("errMsg", errMsg);
					return modelAndView;
				}
			}
		}

        EdocSummary edocSummary = new EdocSummary();
        edocSummary.setIdIfNew(); 
        bind(request, edocSummary);
        
        //设置公文类型,党务还是政务的
        String edocGovType = request.getParameter("edocGovType");
        if("party".equals(edocGovType)){
        	String party = request.getParameter("my:party");
        	edocSummary.setParty(party);
        }else if("administrative".equals(edocGovType)){
        	String administrative = request.getParameter("my:administrative");
        	edocSummary.setAdministrative(administrative);
        }
        
        
        /***** puyc**区分 分发和拟文 分发，收文的summaryId *****/
		String recSummaryIdStr = request.getParameter("recSummaryIdVal");
		if (Strings.isNotBlank(recSummaryIdStr) && !"-1".equals(recSummaryIdStr)) {
			List<EdocSummaryRelation> list = this.edocSummaryRelationManager.findEdocSummaryRelation(Long.parseLong(recSummaryIdStr));
			if (list != null) {
				this.edocSummaryRelationManager.updateEdocSummaryRelation(list, Long.parseLong(recSummaryIdStr), edocSummary.getId());
			}
		}
		/***** puyc**区分 分发和拟文 分发，收文的summaryId end *****/
      
        
        DataUtil.requestToSummary(request,edocSummary,formId);
        
        //检查是否有调用此模板的权限
        boolean isTemplate=templeteManager.hasAccSystemTempletes(edocSummary.getTempleteId(), user.getId());
        /*if(isTemplate==false)
        {//没有公文发起权不能发送
        	ModelAndView modelAndView = new ModelAndView("common/redirect");
        	String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","alert_not_edoctempleteload");
        	modelAndView.addObject("redirectURL","/edocController.do?method=newEdoc&edocType="+edocSummary.getEdocType());
        	modelAndView.addObject("errMsg",errMsg);
        	modelAndView.addObject("errMsgAlert",true);
        	//?method=newEdoc&edocType="+edocType;
        	return modelAndView;
        } */
        
        // 将公文流水号（内部文号）自动增1
        // add by handy,2007-10-16
        //if("new_form".equals(comm))
        //{
       // edocInnerMarkDefinitionManager.getInnerMark(edocSummary.getEdocType(), user.getAccountId(), true);
        //}
        //edocSummary.setSerialNo(serialNo);    
        
        // 处理公文文号
        // 如果公文文号为空，不做任何处理
        String docMark = edocSummary.getDocMark();
        try {
        	docMark=this.registDocMark(edocSummary.getId(), docMark, 1,edocSummary.getEdocType(),false,EdocEnum.MarkType.edocMark.ordinal());
        }catch(EdocMarkHistoryExistException e) {
        	//签报提交时如果文号存在
        	ModelAndView modelAndView = new ModelAndView("common/redirect");
        	String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource",e.getErrorCode());
        	modelAndView.addObject("redirectURL",BaseController.REDIRECT_BACK);
        	modelAndView.addObject("errMsg",errMsg);
        	modelAndView.addObject("errMsgAlert",true);
        	//?method=newEdoc&edocType="+edocType;
        	return modelAndView;
        }
        if(docMark!=null){edocSummary.setDocMark(docMark);}
        
        //处理第二个公文文号
        docMark = edocSummary.getDocMark2();
        docMark=this.registDocMark(edocSummary.getId(), docMark, 2,edocSummary.getEdocType(),false,EdocEnum.MarkType.edocMark.ordinal());
        if(docMark!=null){edocSummary.setDocMark2(docMark);}
        
        //内部文号
        String serialNo = edocSummary.getSerialNo();
        serialNo=this.registDocMark(edocSummary.getId(), serialNo, 3,edocSummary.getEdocType(),false,EdocEnum.MarkType.edocInMark.ordinal());
        if(serialNo!=null){edocSummary.setSerialNo(serialNo);}
        
        Map<String, Object> options = new HashMap<String, Object>();

        EdocEnum.SendType sendType = EdocEnum.SendType.normal;

        //是否重复发起
        if (null != request.getParameter("resend") && !"".equals(request.getParameter("resend"))) {
            sendType = EdocEnum.SendType.resend;            
        }

        //是否转发
        if (null != request.getParameter("forward") && !"".equals(request.getParameter("forward"))) {
            sendType = EdocEnum.SendType.forward;
            //是否转发意见
            boolean isForwardOpinion = "true".equals(request.getParameter("isForwardOpinion"));
            //转发人附言
            String additionalComment = request.getParameter("additionalComment");
            //TODO 转发人追加的附件

            options.put("isForwardOpinion", isForwardOpinion);
            options.put("additionalComment", additionalComment);
        }

        String note = request.getParameter("note");//发起人附言
        EdocOpinion senderOninion = new EdocOpinion();
        senderOninion.setContent(note);
        senderOninion.setIdIfNew();
        String trackMode =request.getParameter("isTrack");
        boolean track = "1".equals(trackMode) ? true : false;
        senderOninion.affairIsTrack = track;
        senderOninion.setAttribute(1);
        senderOninion.setIsHidden(false);
        senderOninion.setCreateUserId(user.getId());
        senderOninion.setCreateTime(new Timestamp(System.currentTimeMillis()));
        senderOninion.setPolicy(request.getParameter("policy"));
        senderOninion.setOpinionType(EdocOpinion.OpinionType.senderOpinion.ordinal());
        senderOninion.setNodeId(0);


        EdocBody body = new EdocBody();
        bind(request, body);
        body.setId(UUIDLong.longUUID());
        String tempStr=request.getParameter("bodyType");
        body.setContentType(tempStr);        
        Date bodyCreateDate = Datetimes.parseDatetime(request.getParameter("bodyCreateDate"));
        if (bodyCreateDate != null) {
            body.setCreateTime(new Timestamp(bodyCreateDate.getTime()));
        }
        
//      从request对象取到选人信息
        FlowData flowData = FlowData.flowdataFromRequest();
        //角色匹配
//        String[] manualSelectNodeId = request.getParameterValues("manual_select_node_id");
//        Map<String, String[]> map = new HashMap<String, String[]>();
//        if(manualSelectNodeId != null){
//            for(String node : manualSelectNodeId){
//                String[] people = request.getParameterValues("manual_select_node_id" + node);
//
//                map.put(node, people);
//            }
//        }
        Map<String, String[]> map = PopSelectParseUtil.getPopNodeSelectedValues(popNodeSelected);
        
        //分枝 开始
//        if(allNodes != null){
//        	Map<String,String> condition = new HashMap<String,String>();
//        	String[] nodes = StringUtils.split(allNodes,":");
//        	String result = "";
//        	if(nodes != null){
//        		for(String node:nodes){
//        			result = request.getParameter("condition"+node);
//        			result = "on".equals(result)?"false":"true";    //传递给后台的isDelete属性，所以要取反
//        			condition.put(node, result);
//        			if("true".equals(result))
//        				map.remove(node);
//        		}
//        		flowData.setCondition(condition);
//        	}
//        }
        Map<String,String> condition = PopSelectParseUtil.getPopNodeConditionValues(popNodeCondition, map);
        flowData.setCondition(condition);
        //分支 结束

        flowData.setAddition(map);
        
//      更新自定义节点的引用
        String[] policys = request.getParameterValues("policys");
        String[] itemNames = request.getParameterValues("itemNames");
        ColHelper.setPolicy(policys, itemNames, flowData);
        //删除原有附件
        if (!edocSummary.isNew()) {
            this.attachmentManager.deleteByReference(edocSummary.getId());
        }
        
        //test code begin        
        edocSummary.setState(Constant.flowState.run.ordinal());
        edocSummary.setCreateTime(new Timestamp(System.currentTimeMillis()));
        if(edocSummary.getStartTime()==null){
        	edocSummary.setStartTime(new Timestamp(System.currentTimeMillis()));
        }
        edocSummary.setStartUserId(user.getId());
        edocSummary.setFormId(Long.parseLong(request.getParameter("edoctable")));
        OrgManager orgManager = (OrgManager) ApplicationContextHolder.getBean("OrgManager");
        V3xOrgMember member = orgManager.getEntityById(V3xOrgMember.class, edocSummary.getStartUserId());
        edocSummary.setStartMember(member);
        //如果公文单无登记人，自动赋上登记节为发起人。yangzd
        if(request.getParameter("my:create_person")==null)
        {
        	edocSummary.setCreatePerson(user.getName());
        }
        //yangzd
        if(edocSummary.getOrgAccountId()==null){
        	edocSummary.setOrgAccountId(user.getLoginAccount());
        }
        edocSummary.setOrgDepartmentId(getEdocOwnerDepartmentId(edocSummary.getOrgAccountId()));
        body.setIdIfNew();
        if(body.getCreateTime()==null)
        {
        	body.setCreateTime(new Timestamp(System.currentTimeMillis()));
        }
        body.setLastUpdate(new Timestamp(System.currentTimeMillis()));
        //test code end 
        //保存附件        
        String attaFlag = attachmentManager.create(ApplicationCategoryEnum.edoc, edocSummary.getId(), edocSummary.getId(), request);
        if(com.seeyon.v3x.common.filemanager.Constants.isUploadLocaleFile(attaFlag)){
        	edocSummary.setHasAttachments(true);
        	
        	//-------------------changyi 增加公文元素中的附件信息--------------------------------
        	//这里只能获得 拟文人所上传的附件 (需要去看下 getByReference方法内部的实现) 
        	List<Attachment> attachmentList = attachmentManager.getByReference(edocSummary.getId());
        	//这里用StringBuffer
        	StringBuffer str = new StringBuffer();
        	for(int i = 0;i<attachmentList.size();i++){
        		Attachment att = attachmentList.get(i);
        		String filename = att.getFilename();
        		if(filename.lastIndexOf(".")>-1){
        			filename = filename.substring(0,filename.lastIndexOf("."));
        		}
        		str.append(filename+",");
        	}
        	edocSummary.setAttachments(str.toString());
        }                     
        boolean isNew = edocSummary.isNew();    
        Long affairId = 0L;
        try {
            affairId = edocManager.runCase(flowData, edocSummary, body, senderOninion, sendType, options,comm,agentToId);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("发起公文流程异常",e);
        }             
        //跟踪
        String trackMembers = request.getParameter("trackMembers");
        String trackRange = request.getParameter("trackRange");
        //不跟踪 或者 全部跟踪的时候不向部门跟踪表中添加数据，所以将下面这个参数串设置为空。
        if(!track || "1".equals(trackRange)) trackMembers = "";
        setTrack(affairId, track, trackMembers);
        
        this.saveColSupervise(request, response, edocSummary, isNew,true);    
         
        //来文登记,更新登记时间，给签收人发送消息        
        /*if("register".equals(comm) && exchangeIdStr!=null && !"".equals(exchangeIdStr))
        {
			if (isCanBeRegisted) {
				Long exchangeId = Long.parseLong(exchangeIdStr);
				recieveEdocManager.registerRecieveEdoc(exchangeId);
			}
        }  */
        
        //通知全文检索不入库
        DateSharedWithWorkflowEngineThreadLocal.setNoIndex(); 
		//全文检索入库
        add2Index(edocSummary.getHasArchive(),edocSummary.getId());
        // lijl添加2011-10-13,对Edoc_Register进行修改,并修改edoc_summary中的sub_edoc_type类型--------------Start
		// 修改EdocRegister中的数据
        if(1==edocSummary.getEdocType()){
        	if(edocRegister!=null) {
        		//edocRegister.setDistributerId(user.getId());//分发人ID
        		//edocRegister.setDistributer(user.getName());//分发人
        		edocRegister.setDistributeDate(new java.sql.Date(new Date().getTime()));//分发时间
        		edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.Distributed.ordinal());//将状态设置为"已分发"
        		edocRegister.setDistributeEdocId(edocSummary.getId());
        		edocRegisterManager.update(edocRegister);
        		// 添加Edoc_Summary中process_type状态
        		edocSummary.setProcessType(processType);
        		edocSummaryManager.saveOrUpdateEdocSummary(edocSummary);
        		//wangjingjing 更新分发待办事件 begin
        		Object[][] wheres = new Object[3][2];
        		wheres[0] = new Object[]{"app", ApplicationCategoryEnum.edocRecDistribute.getKey()};
        		wheres[1] = new Object[]{"objectId", edocRegister.getId()};
        		wheres[2] = new Object[]{"memberId", edocRegister.getDistributerId()};
        		Map columns = new HashMap();
        		columns.put("state", StateEnum.col_done.getKey());
        		columns.put("subObjectId", edocSummary.getId());
        		affairManager.update(columns, wheres);
		        //wangjingjing end
        	}
        }
        
        /* puyc 关联收文 */
		Long sendSummaryId = edocSummary.getId();// 发文Id 
		String relationRecIdStr = request.getParameter("relationRecId"); // 在分发的时候没有值
		String relationRec = request.getParameter("relationRecd");
		////待登记关联发文时，关联id用签收id
		String recieveId = request.getParameter("recieveId");
		String forwordType = request.getParameter("forwordType");
		
		if (Strings.isNotBlank(relationRec) && "haveYes".equals(relationRec)) {
			EdocSummaryRelation edocSummaryRelation = new EdocSummaryRelation();
			edocSummaryRelation.setIdIfNew();
			edocSummaryRelation.setSummaryId(sendSummaryId);// 发文Id
			edocSummaryRelation.setRelationEdocId(Long
					.parseLong(relationRecIdStr));// 收文Id
			edocSummaryRelation.setEdocType(0);// 发文Type
			this.edocSummaryRelationManager
					.saveEdocSummaryRelation(edocSummaryRelation);
		}

		/* puyc 关联发文 */
		String relationSend = request.getParameter("relationSend");
		if (Strings.isNotBlank(relationSend) && "haveYes".equals(relationSend)) { 
			EdocSummaryRelation edocSummaryRelation = new EdocSummaryRelation();
			edocSummaryRelation.setIdIfNew();
			if(Strings.isNotBlank(recieveId)){
				edocSummaryRelation.setSummaryId(Long.parseLong(recieveId));// 签收Id
			}else{
				edocSummaryRelation.setSummaryId(Long.parseLong(relationRecIdStr));// 收文Id
			}
			edocSummaryRelation.setRelationEdocId(sendSummaryId);// 发文Id
			edocSummaryRelation.setEdocType(1);// 收文Type
			//changyi 加上转发人ID
			edocSummaryRelation.setMemberId(user.getId());
			if("registered".equals(forwordType)){
				edocSummaryRelation.setType(1);
			}else if("waitSent".equals(forwordType)){
				edocSummaryRelation.setType(2);
			}
			this.edocSummaryRelationManager
					.saveEdocSummaryRelation(edocSummaryRelation);
		}
		/* puyc 收文关联发文 end */
		
        //return super.redirectModelAndView("/edocController.do?method=listIndex&from=listSent&controller=edocController.do&edocType="+edocSummary.getEdocType());
        String pageview = request.getParameter("pageview"); 
		PrintWriter out = response.getWriter();
		// super.printV3XJS(out);
		out.println("<script>");
		if("listReaded".equals(pageview)){
			out.println("if(window.dialogArguments) {"); // 弹出
			out.println("  	window.returnValue = \"true\";");
			out.println("  	window.close();");
			out.println("} else {");
			out.println("	parent.parent.location.href='edocController.do?method=listIndex&controller=edocController.do&from=listReaded&edocType="+edocSummary.getEdocType()+"'");
			out.println("}");
		}else if("listReading".equals(pageview)){
			out.println("if(window.dialogArguments) {"); // 弹出
			out.println("  	window.returnValue = \"true\";");
			out.println("  	window.close();");
			out.println("} else {");
			out.println("	parent.parent.location.href='edocController.do?method=listIndex&controller=edocController.do&from=listReading&edocType="+edocSummary.getEdocType()+"'");
			out.println("}");
		}
//		else if("transmitSend".equals(comm)){
//			out.println("window.close();");
//		}
		else{
			//int subType = Strings.isBlank(request.getParameter("subType"))?-1:Long.parseLong(request.getParameter("subType"));
			if("agent".equals(request.getParameter("app")) && edocRegister!=null && user.getId()!=edocRegister.getRegisterUserId()) {//代理人跳转到代理事项
				out.println("if(parent.dialogArguments || window.dialogArguments) {");
				out.println("  window.returnValue = \"true\";");
				out.println("  	window.close();");
				out.println("} else {");
				out.println("	parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';");
				out.println("}");
			} else {
				String from = Strings.isBlank(request.getParameter("from"))?"listSent":request.getParameter("from");
				out.println("if(parent.dialogArguments || window.dialogArguments) {");
				out.println("  window.returnValue = \"true\";");
				out.println("  	window.close();");
				out.println("} else {");
				out.println("	parent.parent.location.href='edocController.do?method=listIndex&controller=edocController.do&from="+from+"&edocType="+edocSummary.getEdocType()+"'");
				out.println("}");
			}
		}
		out.println("</script>");
		return null;
    }
    /**
     * 待分发-阅文批处理
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView readBatch(HttpServletRequest request, HttpServletResponse response) throws Exception {	
    	RegisterBody registerBody = null;
        	EdocRegister edocRegister = null;
        	EdocSummary summary = null;//定义表单存储对象
        	EdocBody edocBody = null;
        	User user = CurrentUser.get(); 
        	EdocForm defaultEdocForm=null; //获取默认表单
        	String note=request.getParameter("note");//获取页面附言信息
        	String[] registerId = request.getParameterValues("registerId");//获取登记表ID
        	if(registerId!=null) {//判断页面是否选择，Js有验证，加一层错误提示保险
        		for(int i=0; i<registerId.length; i++) {//批量处理需要办理的待发文单
        			//来文信息
        	        long recieveId = Long.parseLong(registerId[i]);//遍历登记表ID
        	        edocRegister = edocRegisterManager.getEdocRegister(recieveId);//获取登记表信息 //
            		summary=new EdocSummary();//建立新表单
        	        summary.bind(edocRegister);//将登记表值赋给表单信息表
        	        defaultEdocForm = edocFormManager.getDefaultEdocForm(user.getLoginAccount(),1);
        	        summary.setFormId(defaultEdocForm.getId());//将默认表单ID放入表单对象中
        	        String docMark = summary.getDocMark();//获取当前痕迹
        	        if(docMark!=null){summary.setDocMark(docMark);}
        	        //处理文号
        	        docMark = summary.getDocMark2();
        	        docMark=this.registDocMark(summary.getId(), docMark, 2,summary.getEdocType(),false,EdocEnum.MarkType.edocMark.ordinal());
        	        if(docMark!=null){summary.setDocMark2(docMark);}
        	        //内部文号
        	        String serialNo = summary.getSerialNo();
        	        if(serialNo==null){summary.setSerialNo(this.registDocMark(summary.getId(), serialNo, 3,summary.getEdocType(),false,EdocEnum.MarkType.edocInMark.ordinal()));}
        	        summary.setState(Constant.flowState.run.ordinal());//将此流程设为运行状态
        	        summary.setCreateTime(new Timestamp(System.currentTimeMillis()));
        	        if(summary.getStartTime()==null){
        	        	summary.setStartTime(new Timestamp(System.currentTimeMillis()));
        	        }
        	        summary.setStartUserId(user.getId());//
        	        V3xOrgMember member = orgManager.getEntityById(V3xOrgMember.class, summary.getStartUserId());
        	        summary.setStartMember(member);
        	        if(summary.getOrgAccountId()==null){
        	        	summary.setOrgAccountId(user.getLoginAccount());
        	        }
        	        summary.setOrgDepartmentId(getEdocOwnerDepartmentId(summary.getOrgAccountId()));
        	        summary.setProcessType(Long.valueOf("2"));
        	        //装载公文正文
        	        registerBody = edocRegisterManager.findRegisterBodyByRegisterId(recieveId);
        	        edocBody = new EdocBody();
        	        edocBody.setIdIfNew();
        	        if(edocBody.getCreateTime()==null)
        	        {
        	        	edocBody.setCreateTime(new Timestamp(System.currentTimeMillis()));
        	        }
        	        edocBody.setContentType(registerBody==null?"HTML":registerBody.getContentType());
        	        edocBody.setLastUpdate(new Timestamp(System.currentTimeMillis()));
        	        if(summary !=null && edocRegister!=null) {    	        	
        				//增加正文文件和v3x_file
            	        try {
            	        	if(registerBody.getContent()!=null){
            	        		if(!"HTML".equals(registerBody.getContentType())) {
            						//复制正文及复制v3x_file表数据
            	        			V3XFile file=null;
            	        			try{
            						   file = fileManager.clone(Long.parseLong(registerBody.getContent()), true);
	            						file.setFilename(file.getId().toString());
	            						fileManager.update(file);
	            						edocBody.setContent(file.getId().toString());
            	        			}catch(Exception e){
            	        				log.error("复制公文登记正文错误！", e);
            	        			}
            						//复制印章什么的？
            					}
            	        	}
        					//增加附件
            				this.attachmentManager.copy(summary.getId(), summary.getId(), edocRegister.getId(), edocRegister.getId(), ApplicationCategoryEnum.edocRegister.ordinal());//附件
            	    	    FlowData flowData = FlowData.flowdataFromRequest();
            	    	    BPMSeeyonPolicy seeyonPolicy = new BPMSeeyonPolicy("yuedu", "阅读");
            	            flowData.setSeeyonPolicy(seeyonPolicy);
            	    	    String processId = null;
            	            BPMProcess process = null;
            	            //获得流程模板定义信息
            	            if(!flowData.isEmpty()){//如果流程定义数据不为空
            	    	        if(flowData.getXml() == null || "".equals(flowData.getXml())){
            	    		        //根据选人界面传来的people生成流程定义XML
            	    		        processId = ColHelper.saveOrUpdateProcessByFlowData(flowData, processId, false);
            	    		        //从内存中流程定义对象
            	    		        process = ColHelper.getProcess(processId);
            	    		        //从内存中删除该流程定义对象
            	    		        ColHelper.deleteReadyProcess(processId);
            	    		        String caseProcessXML = process.toXML();
            	    		        if(StringUtils.isNotBlank(caseProcessXML)){
            	    		        	caseProcessXML = ColHelper.trimXMLProcessor(caseProcessXML);
            	    					flowData.setXml(caseProcessXML);
            	    		        } 
            	    	        }else{
            	    	        	process = flowData.toBPMProcess();
            	    	        }
            	            }else{//否则从流程实例中获得流程模板定义信息
            	            	processId = request.getParameter("processId");
            	            	process = ColHelper.getCaseProcess(processId);
            	            }
            	            EdocOpinion senderOninion = new EdocOpinion();//创建意见表对象
            	            senderOninion.setContent(note);//保存页面意见信息
            	            senderOninion.setIdIfNew();//创建新的ID
            	            String trackMode =request.getParameter("isTrack");
            	            boolean track = "1".equals(trackMode) ? true : false;
            	            senderOninion.affairIsTrack = track;
            	            senderOninion.setAttribute(1);
            	            senderOninion.setIsHidden(false);
            	            senderOninion.setCreateUserId(user.getId());
            	            senderOninion.setCreateTime(new Timestamp(System.currentTimeMillis()));
            	            senderOninion.setPolicy(request.getParameter("policy"));
            	            senderOninion.setOpinionType(EdocOpinion.OpinionType.senderOpinion.ordinal());
            	            senderOninion.setNodeId(0);
            	            String comm="new_form";
            	            Long agentToId = null;
            	            Map<String, Object> options = new HashMap<String, Object>(); 
            	            //获取页面附言
            	            String additionalComment = note;
            	            options.put("additionalComment", additionalComment);
            	            EdocEnum.SendType sendType = EdocEnum.SendType.normal;
            	                sendType = EdocEnum.SendType.normal;
            	                long affairId=-1; 
            	            try {
            	            	if(summary.getDeadline()==-1L){
                	            	//GOV-3414  【公文管理】-【收文管理】-【分发】-【待分发】，阅文批处理处理的收文，流程中人员收到的提示消息有误  
                	            	summary.setDeadline(0L);
            	            	}
            	            	 affairId = edocManager.runCase(flowData, summary, edocBody, senderOninion,sendType, options,comm,agentToId);
            	            } catch (Exception e) {
            	                log.error("发起公文流程异常",e);
            	            }       
            	            setTrack(affairId, track, "");
    	            	   //edocSummaryManager.saveOrUpdateEdocSummary(summary);
        				} catch(Exception e) {
        					log.error("", e);
        				}
        	        }
        	        edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.Distributed.ordinal());//改成已分发
        	        edocRegister.setDistributeEdocId(summary.getId());
        	        edocRegister.setDistributeDate(new java.sql.Date(summary.getStartTime().getTime()));
        	        edocRegisterManager.update(edocRegister);//修改登记表状态
        	        
        	        Object[][] wheres = new Object[3][2];
            		wheres[0] = new Object[]{"app", ApplicationCategoryEnum.edocRecDistribute.getKey()};
            		wheres[1] = new Object[]{"objectId", edocRegister.getId()};
            		wheres[2] = new Object[]{"memberId", edocRegister.getDistributerId()};
            		Map columns = new HashMap();
            		columns.put("state", StateEnum.col_done.getKey());
            		columns.put("subObjectId", summary.getId());
            		affairManager.update(columns, wheres);
            	}
        	 }                                 
        	return super.redirectModelAndView("edocController.do?method=listDistribute&edocType=1&list=aistributining&btnType=2");
         }
    /**
     * 跟踪相关设置
     * @param affairId : affairiD
     * @param isTrack :是否设置了跟踪
     * @param trackMembers ：部门跟踪人员的ID串
     */
    private void setTrack(Long affairId,boolean isTrack,String trackMembers){
    	 List<Long> members = new ArrayList<Long>();
         if(Strings.isNotBlank(trackMembers)){
         	String[] m = trackMembers.split(",");
         	for(String s : m){
         		members .add(Long.valueOf(s));
         	}
         }
         colManager.changeTrack(affairId, isTrack,members);
    }
    /**
     * 增加全文检索记录
     * @param hasArchive
     * @param summaryId
     */
    private void add2Index(boolean hasArchive ,Long summaryId){
    	if(IndexInitConfig.hasLuncenePlugIn()){
			try {
				indexManager.index(((IndexEnable)edocManager).getIndexInfo(summaryId));
			}catch (Exception e) {
				log.warn(e.getMessage());
			}
		}
    }
    public ModelAndView sendImmediate(HttpServletRequest request,HttpServletResponse response) throws Exception 
    {
    	User user = CurrentUser.get();
    	String[] _summaryIds = request.getParameterValues("id");
    	String[] _affairIds = request.getParameterValues("affairId");
    	String edocType=request.getParameter("edocType");
    	//json格式的字符串:选人
    	String popNodeSelected = request.getParameter("popNodeSelected");
    	//json格式的字符串:条件分支
    	String popNodeCondition = request.getParameter("popNodeCondition");
    	//json格式的字符串:新流程信息
    	String popNodeNewFlow = request.getParameter("popNodeNewFlow");
    	if(log.isInfoEnabled()){
    		log.info("popNodeSelected:="+popNodeSelected);
        	log.info("popNodeCondition:="+popNodeCondition);
        	log.info("popNodeNewFlow:="+popNodeNewFlow);
    	}
    	String subType = Strings.isBlank(request.getParameter("subType"))?"":request.getParameter("subType");
    	StringBuffer message = new StringBuffer(); 
    	//StringBuffer msgErr = new StringBuffer();
    	boolean sentFlag = false;
    	PrintWriter out = response.getWriter();
    	for (int i = 0; i < _summaryIds.length; i++) 
    	{
    		Long summaryId = new Long(_summaryIds[i]);
    		EdocSummary edocSummary = edocManager.getEdocSummaryById(summaryId, false);
    		String processId = edocSummary.getProcessId();

    		//没有流程
    		if (processId == null || "".equals(processId.trim())) {
    			message.append(edocSummary.getSubject()).append("\n");
    			continue;
    		}
    		
    		if(edocFormManager.hasRquiredElement(edocSummary.getFormId())) {
    			out.println("<script>alert('该公文单存在必填项，请编辑后发送。');</script>");
    			out.println("<script>location.href='edocController.do?method=edocFrame&from=listWaitSend&edocType="+edocType+"&subType="+subType+"';</script>");    			
    			return null;
    		}
    		
			FlowData flowData = ColHelper.getRunningProcessPeople(processId);
    		
    		//if(edocSummary.getEdocType()==EdocEnum.edocType.sendEdoc.ordinal())
    		//{
    			//EdocForm ef=edocFormManager.getEdocForm(edocSummary.getFormId());
    			
    			//在退搞箱中发送公文，不用判断公文是否有发送单位了
//    			boolean hasSendUnit=ef.isIncludeEdocElement(13L);
//    			if(hasSendUnit && (edocSummary.getSendToId()==null || "".equals(edocSummary.getSendToId())))
//    			{
//    				msgErr.append(edocSummary.getSubject()).append("\n");
//    				continue;
//    			}
    		//}
    		
//    		String[] manualSelectNodeId = request.getParameterValues("manual_select_node_id");
//    		Map<String, String[]> map = new HashMap<String, String[]>();
//    		if(manualSelectNodeId != null){
//    			for(String node : manualSelectNodeId){
//    				String[] people = request.getParameterValues("manual_select_node_id" + node);
//
//    				map.put(node, people);
//    			}
//    		}
    		
    		Map<String, String[]> map = PopSelectParseUtil.getPopNodeSelectedValues(popNodeSelected);
    		
    		//分支 开始
    		
//    		String allNodes = request.getParameter("allNodes");
//	        if(allNodes != null){
//	        	Map<String,String> condition = new HashMap<String,String>();
//	        	String[] nodes = StringUtils.split(allNodes,":");
//	        	String result = "";
//	        	if(nodes != null){
//	        		for(String node:nodes){
//	        			result = request.getParameter("condition"+node);
//	        			result = "on".equals(result)?"false":"true";    //传递给后台的isDelete属性，所以要取反
//	        			condition.put(node, result);
//	        			if("true".equals(result))
//	        				map.remove(node);
//	        		}
//	        		flowData.setCondition(condition);
//	        	}
//	        }
	        Map<String,String> condition = PopSelectParseUtil.getPopNodeConditionValues(popNodeCondition, map);
	        flowData.setCondition(condition);
			flowData.setAddition(map);			
			//processId = ColHelper.saveOrUpdateProcessByFlowData(flowData, processId, false);
    		
    		//分支 结束
    		
	        if(edocSummary.getOrgAccountId()==null){
	        	edocSummary.setOrgAccountId(user.getLoginAccount());
	        }
    		edocSummary.setOrgDepartmentId(getEdocOwnerDepartmentId(edocSummary.getOrgAccountId()));
    		
    		this.colSuperviseManager.updateStatus(Integer.valueOf(1), edocSummary.getSubject(), user.getId(), user.getName(), Constant.superviseType.edoc.ordinal(), summaryId, Constant.superviseState.supervising.ordinal(), null);
    		DateSharedWithWorkflowEngineThreadLocal.setColSummary(edocSummary);
    		edocManager.sendImmediate(Long.parseLong(_affairIds[i]),edocSummary, flowData);
    		sentFlag = true;
    		
    	
    		 //全文检索
            DateSharedWithWorkflowEngineThreadLocal.setNoIndex();
            add2Index(edocSummary.getHasArchive(),edocSummary.getId());
    		
    	}
    	
    	ModelAndView mv = super.redirectModelAndView("/edocController.do?method=edocFrame&from=listSent&edocType="+edocType);

    	if (message.length() > 0) {
    		WebUtil.saveAlert("alert.sendImmediate.nowf", message.toString());
    		mv = super.redirectModelAndView("/edocController.do?method=edocFrame&from=listWaitSend&edocType="+edocType);
    	}
    	//if (msgErr.length() > 0) {
    	//	WebUtil.saveAlert("alert.sendImmediate.noSendComp", msgErr.toString());
    	//	mv = super.redirectModelAndView("/edocController.do?method=edocFrame&from=listWaitSend&edocType="+edocType);
    	//}
    	
    	return mv;
    }
    
    
    /**
     * 审核公文时，是否修改过文单
     * @param s1
     * @param s2
     * @return
     */
    private boolean isChangeEdocForm(EdocSummary s1,EdocSummary s2){
    	boolean flag = false;
    	Method[] methods = EdocSummary.class.getDeclaredMethods();
    	for(Method method : methods){
    		Class[] p = method.getParameterTypes();
			int parameterCount = p.length;
			//只比较get方法，并且其中关于时间的都不比较
    		if(method.getName().startsWith("get") 
    		  && !method.getName().endsWith("Time")
    		  && !method.getName().endsWith("Date")
    		  && parameterCount == 0){
    			
        		Object value1 = null;
        		Object value2 = null;
				try {
					value1 = method.invoke(s1);
					value2 = method.invoke(s2);
				} catch (Exception e) {
					e.printStackTrace();
				} 
        		
        		if(value1 != null && value2 != null && !value1.equals(value2)){
//        			System.out.println(method.getName()+"   "+value1+"   "+value2);
        			flag = true;
        			break;
        		}
    		} 
    	}
    	return flag;
    }
    
    private ConfigItem getNewConfigItemForSaveOldFormId(String item, String value, Long accountId)
	{
		ConfigItem edocItem=new ConfigItem();
		edocItem.setIdIfNew();
		edocItem.setConfigCategory(BEFORE_SHANGKA_FORMID);
		edocItem.setConfigItem(item);
		edocItem.setExtConfigValue(value);
		edocItem.setOrgAccountId(accountId);
		edocItem.setCreateDate(new Timestamp(new Date().getTime()));
		return edocItem;
	}
    
    /*修改文单后，保存修改的数据*/
    public ModelAndView updateFormData(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	Boolean ret=false;
    	User user = CurrentUser.get();
    	boolean updateMark = false;
    	long summaryId=Long.parseLong(request.getParameter("summaryId"));    	
        EdocSummary edocSummary = edocManager.getEdocSummaryById(summaryId,false);
        Long affairId = Long.valueOf(request.getParameter("affairId")) ; 
        Affair affair = affairManager.getById(affairId) ;
        long formId=Long.parseLong(request.getParameter("edoctable").trim());       
        try{
        	//克隆一个对象，以和改变后的相比较
        	EdocSummary copyEdocSummary = (EdocSummary)edocSummary.clone();
        	
        	DataUtil.requestToSummary(request,edocSummary,formId); 
        	
        	//山西太原市政府二开  签报时判断是否当前节点为上卡操作  郝后成   2012-07-27
        	if(affair.getNodePolicy().equals("上卡") && formId != copyEdocSummary.getFormId()){
        		
        		ConfigItem edocFormItem = configManager.getConfigItem(BEFORE_SHANGKA_FORMID ,String.valueOf(summaryId), user.getAccountId());
        		if(edocFormItem == null){
        			edocFormItem = this.getNewConfigItemForSaveOldFormId(String.valueOf(summaryId),String.valueOf(copyEdocSummary.getFormId()), user.getAccountId());
        			configManager.addConfigItem(edocFormItem);
        		}else{
        			edocFormItem.setExtConfigValue(String.valueOf(copyEdocSummary.getFormId()));
        			configManager.updateConfigItem(edocFormItem);
        		}
        		
        	}
        	
          // 处理公文文号
          // 如果公文文号为空，不做任何处理
          String docMark = edocSummary.getDocMark();
          if(docMark!=null && !"".equals(docMark))
          {
        	 // edocMarkManager.disconnectionEdocSummary(edocSummary.getId(),1);
        	  try { 
        		  docMark=this.registDocMark(edocSummary.getId(), docMark, 1,edocSummary.getEdocType(),true,EdocEnum.MarkType.edocMark.ordinal());
        	  }catch(EdocMarkHistoryExistException e) {
        		  String errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource",e.getErrorCode());
        		  response.getWriter().print("result=historyMarkExist:"+errMsg); 
        		  return null;
        	  }
        	  if(docMark!=null){edocSummary.setDocMark(docMark);}
        	  updateMark = true;
          }          
          //处理第二个公文文号
          docMark = edocSummary.getDocMark2();
          if(docMark!=null && !"".equals(docMark))
          {
        	 // edocMarkManager.disconnectionEdocSummary(edocSummary.getId(),2);
        	  docMark=this.registDocMark(edocSummary.getId(), docMark, 2,edocSummary.getEdocType(),true,EdocEnum.MarkType.edocMark.ordinal());
        	  if(docMark!=null){edocSummary.setDocMark2(docMark);}
        	  updateMark = true;
          }
          
          //处理内部文号
          String serialNo = edocSummary.getSerialNo();
          if(serialNo!=null && !"".equals(serialNo))
          {
        	//  edocMarkManager.disconnectionEdocSummary(edocSummary.getId(),3);
        	  serialNo=this.registDocMark(edocSummary.getId(), serialNo, 3,edocSummary.getEdocType(),true,EdocEnum.MarkType.edocInMark.ordinal());
        	  if(serialNo!=null){edocSummary.setSerialNo(serialNo);}
          }
          
          
          
          // 加日志1.文号修改
          if(updateMark){
        	  //operationlogManager.insertOplog(summaryId, ApplicationCategoryEnum.edoc, EactionType.LOG_EDOC_UPDATE_MARK, 
        	  //    EactionType.LOG_EDOC_UPDATE_MARK_DESCRIPTION,user.getName(), edocSummary.getSubject());
          }
          //加日志2.修改文单
         // operationlogManager.insertOplog(summaryId, formId, ApplicationCategoryEnum.edoc, EactionType.LOG_EDOC_UPDATE_CONTENT, EactionType.LOG_EDOC_UPDATE_CONTENT_DESCRIPTION, user.getName(), edocSummary.getSubject());
         
          BPMActivity bPMActivity =  EdocHelper.getBPMActivityByAffair(affair) ;
          String isOnlyModifyWordNo=request.getParameter("isOnlyModifyWordNo");
          if("true".equals(isOnlyModifyWordNo)){
        	  this.processLogManager.insertLog(user, Long.valueOf(edocSummary.getProcessId()),Long.valueOf(bPMActivity.getId()),
        			  ProcessLogAction.processEdoc, String.valueOf(ProcessLogAction.ProcessEdocAction.modifyWordNo.getKey())) ;
          }else{
        	  this.processLogManager.insertLog(user, Long.valueOf(edocSummary.getProcessId()),Long.valueOf(bPMActivity.getId()),
        			  ProcessLogAction.processEdoc, String.valueOf(ProcessLogAction.ProcessEdocAction.modifyForm.getKey())) ;
          }
          edocManager.update(edocSummary);  
          
          //判断是否修改了文单
          if(isChangeEdocForm(edocSummary,copyEdocSummary)){
        	  appLogManager.insertLog(user, AppLogAction.Edoc_Form_update, user.getName(),affair.getSubject());
    	  }
          
          
          //暂存待办时更新affair中的标题和紧急程度
          Map<String,Object> columns = new HashMap<String,Object>(2);
          columns.put("subject", edocSummary.getSubject());
          if(!Strings.isEmpty(edocSummary.getUrgentLevel()))
        	  columns.put("importantLevel", Integer.parseInt(edocSummary.getUrgentLevel()));
          this.affairManager.update("objectId",edocSummary.getId(),columns);
          ret=true;
          docHierarchyManager.updatePigeHoleFile(edocSummary.getId(), ApplicationCategoryEnum.edoc.getKey(), user.getId()) ;
         
        }catch(Exception e)
        {
        	log.error(e);
        	//e.printStackTrace();
        }                
        response.getWriter().print("result="+ret);                
    	return null;
    }
    
    
    /**
     * 保存待发
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();    

		// 保存待发时登记外来文
		boolean isRegistCanBeSaved = true; 
		EdocRegister edocRegister = null;
		long registerId = Strings.isBlank(request.getParameter("registerId"))?-1:Long.parseLong(request.getParameter("registerId"));
		String comm = request.getParameter("comm");
		if ("distribute".equals(comm) && registerId!=-1) {
			edocRegister = edocRegisterManager.findRegisterById(registerId);
			if(edocRegister != null) {
				// 保存分发记公文，判断当前操作人是否可以保存此待登记公文
				Long recordRegisterUserId = edocRegister.getDistributerId();
				if (recordRegisterUserId.longValue() != user.getId()) {
					// 公文分发人已经转换
					isRegistCanBeSaved = false;
					String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasChanged_distribute");
					PrintWriter out = response.getWriter();
					// super.printV3XJS(out);
					out.println("<script>");
					out.println("alert(\"" + errMsg + "\")");
					out.println("if(window.dialogArguments){"); // 弹出
					out.println("  window.returnValue = \"true\";");
					out.println("  window.close();");
					out.println("}else{");
					if("agent".equals(request.getParameter("app"))) {//无权查看主题，代理页面跳转到代理事项。
	                	out.println("	parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';");
	                } else {//无权查看主题，被代理页面跳转到代理事项。
	                	out.println("	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType=1';");
	                }
					out.println("}");
					out.println("");
					out.println("</script>");
					return null;
				}
				if (edocRegister.getIsRetreat() == 1) {
					// 公文已经回退
					isRegistCanBeSaved = false;
					String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_hasBeStepBack_already");
					PrintWriter out = response.getWriter();
					// super.printV3XJS(out);
					out.println("<script>");
					out.println("alert(\"" + errMsg + "\")");
					out.println("if(window.dialogArguments){"); // 弹出
					out.println("  window.returnValue = \"true\";");
					out.println("  window.close();");
					out.println("}else{");
					if("agent".equals(request.getParameter("app"))) {//无权查看主题，代理页面跳转到代理事项。
	                	out.println("	parent.parent.parent.location.href='main.do?method=morePending4App&app=agent';");
	                } else {//无权查看主题，被代理页面跳转到代理事项。
	                	out.println("	parent.parent.location.href='edocController.do?method=listIndex&from=listSent&edocType=1';");
	                }
					out.println("}");
					out.println("");
					out.println("</script>");
					return null;
				}
				if (edocRegister.getDistributeState() == EdocNavigationEnum.EdocDistributeState.Distributed.ordinal()) {// 公文已经分发
					isRegistCanBeSaved = false;
					ModelAndView modelAndView = new ModelAndView("common/redirect");
					String errMsg = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource", "alert_has_registe");
					modelAndView.addObject("redirectURL", BaseController.REDIRECT_BACK);
					modelAndView.addObject("errMsg", errMsg);
					return modelAndView;
				}
			}
		}

        EdocSummary summary = new EdocSummary();
        bind(request, summary);
        if(summary.isNew()) {
        	summary.setId(Long.parseLong(request.getParameter("summaryId")));
        }
        boolean isNew = summary.isNew();
        summary.setIdIfNew();
        
        long formId=Long.parseLong(request.getParameter("edoctable"));
        
        DataUtil.requestToSummary(request,summary,formId);
        
        // 将公文流水号（内部文号）自动增1
        // add by handy,2007-10-16
        //String serialNo = edocInnerMarkDefinitionManager.getInnerMark(summary.getEdocType(), user.getAccountId(), true);
        //summary.setSerialNo(serialNo);      
        
        // 处理公文文号
        // 如果公文文号为空，不做任何处理
        String docMark = summary.getDocMark();
        docMark=this.registDocMark(summary.getId(), docMark, 1,summary.getEdocType(),false,EdocEnum.MarkType.edocMark.ordinal());
        if(docMark!=null){summary.setDocMark(docMark);}
        
        //处理第二个公文文号
        docMark = summary.getDocMark2();
        docMark=this.registDocMark(summary.getId(), docMark, 2,summary.getEdocType(),false,EdocEnum.MarkType.edocMark.ordinal());
        if(docMark!=null){summary.setDocMark2(docMark);}

        //内部文号
        String serialNo = summary.getSerialNo();
        serialNo=this.registDocMark(summary.getId(), serialNo, 3,summary.getEdocType(),false,EdocEnum.MarkType.edocInMark.ordinal());
        if(serialNo!=null){summary.setSerialNo(serialNo);}
        
        String note = request.getParameter("note");//发起人附言
        EdocOpinion senderOninion = new EdocOpinion();
        senderOninion.setContent(note);
        senderOninion.setIdIfNew();
        String trackMode =request.getParameter("isTrack");
        boolean track = "1".equals(trackMode) ? true : false;
        senderOninion.affairIsTrack = track;
        summary.setCanTrack(track?1:0);
        senderOninion.setAttribute(1);
        senderOninion.setIsHidden(false);
        senderOninion.setCreateUserId(user.getId());
        senderOninion.setCreateTime(new Timestamp(System.currentTimeMillis()));
        senderOninion.setPolicy(request.getParameter("policy"));
        senderOninion.setOpinionType(EdocOpinion.OpinionType.senderOpinion.ordinal());
        senderOninion.setNodeId(0);

        EdocBody body = new EdocBody();
        bind(request, body);
        String tempStr=request.getParameter("bodyType");
        body.setContentType(tempStr);
        Date bodyCreateDate = Datetimes.parseDatetime(request.getParameter("bodyCreateDate"));
        if (bodyCreateDate != null) {
            body.setCreateTime(new Timestamp(bodyCreateDate.getTime()));
        }
        body.setIdIfNew();

        //删除原有附件
        if (!summary.isNew()) {
            this.attachmentManager.deleteByReference(summary.getId());
        }
        /*
        FlowData flowData = new FlowData();
        flowData.setDesc_by(FlowData.DESC_BY_XML);
        String xml = request.getParameter("process_xml");
        flowData.setXml(xml);
        */
        FlowData flowData = FlowData.flowdataFromRequest();
        
        
        //      test code begin
        summary.setState(Constant.flowState.run.ordinal());        
        if(summary.getCreateTime()==null)
        {
        	summary.setCreateTime(new Timestamp(System.currentTimeMillis()));
        }
        if(summary.getStartTime() ==  null){
        	summary.setStartTime(new Timestamp(System.currentTimeMillis()));
        }
        summary.setStartUserId(user.getId());
        summary.setFormId(Long.parseLong(request.getParameter("edoctable")));
        OrgManager orgManager = (OrgManager) ApplicationContextHolder.getBean("OrgManager");
        V3xOrgMember member = orgManager.getEntityById(V3xOrgMember.class, summary.getStartUserId());
        summary.setStartMember(member);
        
        body.setIdIfNew();  
        if(body.getCreateTime()==null)
        {
        	body.setCreateTime(new Timestamp(System.currentTimeMillis()));
        }        
        body.setLastUpdate(new Timestamp(System.currentTimeMillis()));        
        //test code end

        //保存附件        
        String attaFlag = this.attachmentManager.create(ApplicationCategoryEnum.edoc, summary.getId(), summary.getId(), request);
        if(com.seeyon.v3x.common.filemanager.Constants.isUploadLocaleFile(attaFlag)){
        	summary.setHasAttachments(true);
        }   
        

        
        this.zcdbSupervise(request, response, summary, isNew,Constant.superviseState.waitSupervise.ordinal(),false);
        
        String saveToBackBox = request.getParameter("saveToBackBox");
        Long affairId = 0L;
        if("true".equals(saveToBackBox)){
        	affairId = edocManager.saveBackBox(flowData, summary, body, senderOninion);  
        }
        else{
        	affairId = edocManager.saveDraft(flowData, summary, body, senderOninion);  
        }
        
        if(summary!=null && summary.getEdocType()==1 && "distribute".equals(comm)) {
    		//lijl添加,修改bug40949点击页面的保存至草稿箱，该公文依然在待分发列表(实际应该进入草稿箱，并在该列表消失)------
        	//0表示保存至草稿箱
        	if(edocRegister!=null){
        		edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.DraftBox.ordinal());//分发草稿
        		edocRegister.setDistributeEdocId(summary.getId());
        		edocRegisterManager.update(edocRegister);
        	}
        	//lijl添加,修改bug40949点击页面的保存至草稿箱，该公文依然在待分发列表(实际应该进入草稿箱，并在该列表消失)--------End       	
        }
        
       //跟踪
        String trackMembers = request.getParameter("trackMembers");
        String trackRange = request.getParameter("trackRange");
        //不跟踪 或者 全部跟踪的时候不向部门跟踪表中添加数据，所以将下面这个参数串设置为空。
        if(!track || "1".equals(trackRange)) trackMembers = "";
        if(!"true".equals(saveToBackBox)){
        	setTrack(affairId, track, trackMembers);
        }
        
        
        //保存待发时登记外来文
        /*if("register".equals(request.getParameter("comm")) && exchangeIdStr!=null && !"".equals(exchangeIdStr))
        {
			if (isRegistCanBeSaved) {
				Long exchangeId = Long.parseLong(exchangeIdStr);
				recieveEdocManager.registerRecieveEdoc(exchangeId);
			}
        }*/
        
       // return super.redirectModelAndView("/edocController.do?method=edocFrame&from=listWaitSend&edocType="+summary.getEdocType());
		PrintWriter out = response.getWriter();
		out.println("<script>");
		
		
		//修复bug GOV-3238 【公文管理】-【发文管理】-【待办】，发文转发时保存至草稿箱后跳转的是空白页面
		//将下面注释掉，可能是以前转发后的页面还是在弹出的新页面中存在的，现在不是了
		//转发 点保存到草稿箱，直接关闭弹出的窗口
//		if("transmitSend".equals(request.getParameter("comm"))){
//			out.println("window.close();");
//		}else 
		if("true".equals(saveToBackBox)){ 
			out.println("if(window.dialogArguments){"); // 弹出
			out.println("  window.returnValue = \"true\";");
			out.println("  window.close();");
			out.println("} else {");
			out.println("	parent.parent.location.href='edocController.do?method=listIndex&controller=edocController.do&from=listWaitSend&list=backBox&edocType="+summary.getEdocType()+"'");
			out.println("}");
		}
		else {
			out.println("if(window.dialogArguments){"); // 弹出
			out.println("  window.returnValue = \"true\";");
			out.println("  window.close();");
			out.println("} else {");
			out.println("parent.parent.location.href='edocController.do?method=listIndex&controller=edocController.do&from=listWaitSend&list=draftBox&edocType="+summary.getEdocType()+"'");
			out.println("}");
		}
		out.println("</script>");
		return null;
    }
    
    
    /**
     * 归档后修改保存
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView saveArchived(HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
    	boolean updateMark = false;
    	long summaryId=Long.parseLong(request.getParameter("summaryId"));    	
        EdocSummary edocSummary = edocManager.getEdocSummaryById(summaryId,false);
        //Long affairId = Long.valueOf(request.getParameter("affairId")) ;
        //Affair affair = affairManager.getById(affairId) ;
        long formId=Long.parseLong(request.getParameter("edoctable"));        
        try{
          DataUtil.requestToSummary(request,edocSummary,formId);
          
          // 处理公文文号
          // 如果公文文号为空，不做任何处理
          String docMark = edocSummary.getDocMark();
          if(docMark!=null && !"".equals(docMark))
          {
        	  try {
        		  docMark=this.registDocMark(edocSummary.getId(), docMark, 1,edocSummary.getEdocType(),true,EdocEnum.MarkType.edocMark.ordinal());
        	  }catch(EdocMarkHistoryExistException e) {
        		  return null;
        	  }
        	  if(docMark!=null){edocSummary.setDocMark(docMark);}
        	  updateMark = true;
          }          
          //处理第二个公文文号
          docMark = edocSummary.getDocMark2();
          if(docMark!=null && !"".equals(docMark))
          {
        	  docMark=this.registDocMark(edocSummary.getId(), docMark, 2,edocSummary.getEdocType(),true,EdocEnum.MarkType.edocMark.ordinal());
        	  if(docMark!=null){edocSummary.setDocMark2(docMark);}
        	  updateMark = true;
          }
          
          //处理内部文号
          String serialNo = edocSummary.getSerialNo();
          if(serialNo!=null && !"".equals(serialNo))
          {
        	  serialNo=this.registDocMark(edocSummary.getId(), serialNo, 3,edocSummary.getEdocType(),true,EdocEnum.MarkType.edocInMark.ordinal());
        	  if(serialNo!=null){edocSummary.setSerialNo(serialNo);}
          }
          
          //正文
          EdocBody body = new EdocBody();
          bind(request, body);
          String tempStr=request.getParameter("bodyType");
          body.setContentType(tempStr);
          Date bodyCreateDate = Datetimes.parseDatetime(request.getParameter("bodyCreateDate"));
          if (bodyCreateDate != null) {
              body.setCreateTime(new Timestamp(bodyCreateDate.getTime()));
          }
          body.setIdIfNew();
          if(body.getCreateTime()==null)
          {
          	body.setCreateTime(new Timestamp(System.currentTimeMillis()));
          }        
          body.setLastUpdate(new Timestamp(System.currentTimeMillis()));     
          
          
          //删除原有附件
          if (!edocSummary.isNew()) {
              this.attachmentManager.deleteByReference(edocSummary.getId());
          }
          //保存附件        
          String attaFlag = this.attachmentManager.create(ApplicationCategoryEnum.edoc, edocSummary.getId(), edocSummary.getId(), request);
          if(com.seeyon.v3x.common.filemanager.Constants.isUploadLocaleFile(attaFlag)){
        	  edocSummary.setHasAttachments(true);
          } else{
        	  edocSummary.setHasAttachments(false);
          }
          
//          BPMActivity bPMActivity =  EdocHelper.getBPMActivityByAffair(affair) ;
//          String isOnlyModifyWordNo=request.getParameter("isOnlyModifyWordNo");
//          if("true".equals(isOnlyModifyWordNo)){
//        	  this.processLogManager.insertLog(user, Long.valueOf(edocSummary.getProcessId()),Long.valueOf(bPMActivity.getId()), ProcessLogAction.processEdoc, String.valueOf(ProcessLogAction.ProcessEdocAction.modifyWordNo.getKey())) ;
//          }else{
//        	  this.processLogManager.insertLog(user, Long.valueOf(edocSummary.getProcessId()),Long.valueOf(bPMActivity.getId()), ProcessLogAction.processEdoc, String.valueOf(ProcessLogAction.ProcessEdocAction.modifyForm.getKey())) ;
//          }
          edocManager.update(edocSummary);
          
          //归档的数据修改（doc_resource,doc_metadata）
          docHierarchyManager.updatePigeHoleFile(edocSummary.getId(), ApplicationCategoryEnum.edoc.getKey(), user.getId()) ;
          
          //新增修改历史记录
          String isModifyContent=request.getParameter("isModifyContent");//是否修改正文
          String isModifyForm=request.getParameter("isModifyForm");//是否修改文单
          String isModifyAtt=request.getParameter("isModifyAtt");//是否修改附件
          EdocArchiveModifyLog modifyLog=new EdocArchiveModifyLog();
          modifyLog.setIdIfNew();
          modifyLog.setSummaryId(summaryId);
          modifyLog.setUpdatePerson(user.getName());
          modifyLog.setUserId(user.getId());
          modifyLog.setUpdateTime(new Date());
          modifyLog.setModifyContent(isModifyContent!=null?Integer.parseInt(isModifyContent):0);
          modifyLog.setModifyForm(isModifyForm!=null?Integer.parseInt(isModifyForm):0);
          modifyLog.setModifyAtt(isModifyAtt!=null?Integer.parseInt(isModifyAtt):0);
          edocArchiveModifyLogManager.saveEdocArchiveModifyLog(modifyLog);
          
		  PrintWriter out = response.getWriter();
		  out.println("<script>");
		  out.println("location.href='edocController.do?method=listFinish&edocType=0&list=doneOver&hasArchive=1'");
		  out.println("</script>");
        }catch(Exception e)
        {
        	log.error("公文发文已办结归档修改异常",e);
        	//e.printStackTrace();
        }        
        

		return null;
    }
    
    /**
     * 页面框架
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView edocFrame(HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
    	//String controller=request.getParameter("controller");    	
    	ModelAndView modelAndView = new ModelAndView("edoc/edocFrame");
    	modelAndView.addObject("controller", "edocController.do");
    	//会议纪要转公文 获得会议纪要ID
        String meetingSummaryId = request.getParameter("meetingSummaryId");
        String comm = request.getParameter("comm");
    	String from = request.getParameter("from");
    	if(from!=null &&(from.equals("listRecieve") || from.equals("listFenfa"))) {
            modelAndView.addObject("controller", "exchangeEdoc.do");
        } else {
            modelAndView.addObject("controller", "edocController.do");
        }
    	String edocType=request.getParameter("edocType");
    	modelAndView.addObject("edocType", edocType);

        int iEdocType=-1;
        if(edocType!=null && !"".equals(edocType)) {
            iEdocType=Integer.parseInt(edocType);
        }
        //是否包含“待登记”按钮        
        boolean hasRegistButton=false;
        if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType || EdocEnum.edocType.distributeEdoc.ordinal()==iEdocType) {//收文
            modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
            hasRegistButton=true;
        } else  {
            modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
        }
        int roleEdocType = iEdocType==1?3:iEdocType;
        boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);//公文发起权
        boolean isExchangeRole=EdocRoleHelper.isExchangeRole(); //公文交换权
        modelAndView.addObject("edocType", edocType);        
        modelAndView.addObject("hasRegistButton", hasRegistButton);
        modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
        modelAndView.addObject("isExchangeRole", isExchangeRole);
        modelAndView.addObject("meetingSummaryId", meetingSummaryId);
        modelAndView.addObject("comm", comm);
        
        String nowFrom=request.getParameter("from");
        if(nowFrom!=null && !"".equals(nowFrom) && "newEdoc".equals(nowFrom)){
        	modelAndView.addObject("isNewEdoc", true);
        }
        
        if(from!=null &&from.equals("listFenfa")) {
        	modelAndView.addObject("isFenfa", true);
        }
        if("agent".equals(request.getParameter("app"))) {
        	long affairId = Strings.isBlank(request.getParameter("affairId"))?-1:Long.parseLong(request.getParameter("affairId"));
        	if(affairId != -1) {
        		Affair affair = affairManager.getById(affairId);
        		if(affair!=null && affair.getMemberId()!=CurrentUser.get().getId()) {
        			if(affair.getApp() == 24) {//收文登记
        				hasRegistButton = EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.recEdoc.ordinal());//公文发起权
        				if(!hasRegistButton) {
        					modelAndView.addObject("isAgent", true);
        				}
        			} else if(affair.getApp() == 34) {//收文分发
        				if(!isEdocCreateRole) {
        					modelAndView.addObject("isAgent", true);
        				}
        			}       			
        		}
        	} else {
        		modelAndView.addObject("isAgent", true);
        	}
        }
        
        return modelAndView;
    }
    
    /**
     * 已办公文列表
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listDone(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        String edocType=request.getParameter("edocType");
        int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        params.put("processType", 1);
        String list=request.getParameter("list");
        int iEdocType=-1;
    	if(edocType!=null && !"".equals(edocType))
    	{
    		iEdocType=Integer.parseInt(edocType);
    	}
        ModelAndView modelAndView = new ModelAndView("edoc/listDone");
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());
        List<EdocSummaryModel> queryList = null;  
        if (theMember.getAgentId() == -1)
        {
            /**********组合查询组件调用开始*****************/
        	String comb_condition = request.getParameter("comb_condition");  //组合查询标识
            if(comb_condition!=null && "1".equals(comb_condition) ){
        		EdocSearchModel em=new EdocSearchModel();
        		bind(request, em);
        		if("notFinish".equals(list)) {
        			queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_done.key(),-1);
        		}else {
        			queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_done.key(),params,new int[]{});
        		}
        		modelAndView.addObject("combQueryObj", em);  //设置的查询条件还原到页面
        		modelAndView.addObject("combCondition", "1");
            }else
            /***************组合查询组件调用结束************/
        	if(condition != null && !"".equals(condition) && (Strings.isNotBlank(textfield) || Strings.isNotBlank(textfield1))) {
        		if(condition.equals("cusReceiveTime")){ //如果条件来自自定义分类的时间段，设置查询条件和查询起始时间
        			condition="receiveTime";
        			String[] textfield_condition= edocManager.getTimeTextFiledByTimeEnum(Integer.parseInt(textfield));
        			textfield=textfield_condition[0];
        			textfield1=textfield_condition[1];
        		}
        		if("notFinish".equals(list)) {
        			queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_done.key(), params, -1);
        		}else {
        			queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_done.key(), params);
        		}
        	}
        	if (queryList != null&& !"".equals(condition)) {
        		    modelAndView.addObject("pendingList", queryList);
        	} else{
        		List<EdocSummaryModel> finishedList = null;
    		    if(iEdocType==0){//执行发文查询
    		    	//未办结
    		    	if("notFinish".equals(list)) {
    		    		finishedList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key(), params, -1);
    		    	}else {//全部，已办结在listFinish方法
    		    		finishedList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key(), params);
    		    	}
    		    	 
    		    }else{//执行收文查询
    		    	if("notFinish".equals(list)) {
    		    		finishedList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key(), params, -1);
    		    	}else {
    		    		finishedList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key(), params);
    		    	}
    		    }
    		    modelAndView.addObject("pendingList", finishedList);
    		    //这里逻辑重复，上面已经有condition<>null和==null的逻辑
        		/*if("".equals(condition)){
        			List<EdocSummaryModel> finishedList = null;
      				 finishedList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key());
            	 	modelAndView.addObject("pendingList", finishedList);
        		}else{
            		List<EdocSummaryModel> finishedList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key(),-1);
            		modelAndView.addObject("pendingList", finishedList);
        		}*/
        	}
        }
        else 
        {
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        
        /*
         * 元数据中加载 秘密程度
         * cy add
         */
        Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        colMetadata.put(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);
        
        /*
         * 元数据中加载 紧急程度
         * cy add
         */
        Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        colMetadata.put(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
        
        
    	modelAndView.addObject("edocType", edocType);    	
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
    	}
    	else
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	int roleEdocType = iEdocType==1?3:iEdocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
    	//发文拟文权限
    	boolean isSendEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
    	modelAndView.addObject("isSendEdocCreateRole", isSendEdocCreateRole);
    	
        return modelAndView;
    }
    
    

    
    /**
     * 显示自定义类别列表页面
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView customerTypes(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	String isAdminSet = request.getParameter("isAdminSet");
    	
    	ModelAndView modelAndView = new ModelAndView("edoc/edocCustomerType");
    	User user = this.getCurrentUser();
    	//获取单位ID 
    	long loginAccount = user.getLoginAccount(); 
    	//根据发文或收文，获取其节点权限列表
    	//获得当前是 发文还是收文
    	String edocType=request.getParameter("edocType")==null?"0":request.getParameter("edocType");
    	int iEdocType=-1; 

    	List nodeList = null;
    	//发文时 节点列表
    	if(Integer.parseInt(edocType) == EdocCustomerTypeEnum.SEND_NODE_TYPE.ordinal()){
    		nodeList = flowPermManager.getFlowPermsByCategory("edoc_send_permission_policy", loginAccount);
    	}
    	//收文时 节点列表
    	if(Integer.parseInt(edocType) == EdocCustomerTypeEnum.REC_NODE_TYPE.ordinal()){
    		nodeList = flowPermManager.getFlowPermsByCategory("edoc_rec_permission_policy", loginAccount);
    	}
    	
    	//紧急程度
    	Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        modelAndView.addObject(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
        //文件密级
        Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        modelAndView.addObject(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);
        
        //行文类型
        Metadata sendType = metadataManager.getMetadata(MetadataNameEnum.edoc_send_type);
        modelAndView.addObject(MetadataNameEnum.edoc_send_type.toString(), sendType);
        
        
        //还要区分是待办还是已办
    	String from = request.getParameter("from");  
    	if(Strings.isNotBlank(from)){
    		iEdocType = getCustomType(edocType, from);
    	}
        
    	//自定义列表,还是要区分 发文 和 收文
        //用户已勾选 需要显示的 类别列表
		/*CustomerTypeList 和 流程节点POJO 应该是不一样的，在jsp页面中其实 只需要比较他们的 ID 即可*/
		Map map = edocCustomerTypeManager.getUserCustomerTypeList(user,iEdocType,isAdminSet,Integer.parseInt(edocType));
		List customerTypeList = (List)map.get("customerTypeList");
		List timeList = (List)map.get("timeList");
		List sendList = (List)map.get("sendList");
		modelAndView.addObject("nodeList", nodeList);
		modelAndView.addObject("timeList", timeList);
		modelAndView.addObject("sendList", sendList);
		modelAndView.addObject("customerTypeList", customerTypeList);
//		//大类别，页面好处理
//		long bigTypeId = 0;
//		if(customerTypeList.size()>0){
//			bigTypeId = ((EdocCustomerType)customerTypeList.get(0)).getBigTypeId();
//		}
//		modelAndView.addObject("bigTypeId", bigTypeId);
		modelAndView.addObject("edocType", edocType);
    	return modelAndView;
    }

	private int getCustomType(String edocType, String from) {
		int iEdocType = -1;
		if("listPending".equals(from)){
    		if("0".equals(edocType)){
    			iEdocType = EdocCustomConstant.SEND_PENDING;	//发文待办
    		}else{
    			iEdocType = EdocCustomConstant.REC_PENDING;;	//收文待办
    		}
    	}else if("listDone".equals(from)){
    		if("0".equals(edocType)){
    			iEdocType = EdocCustomConstant.SEND_DONE;	//发文已办
    		}else{
    			iEdocType = EdocCustomConstant.REC_DONE;	//收文已办
    		}
    	}else if("listReaded".equals(from)){	//已阅
    		iEdocType = EdocCustomConstant.REC_READED;
    	}
    	if(iEdocType == -1){ 
    		if("0".equals(edocType)){
    			iEdocType = EdocCustomConstant.SEND_ADMIN;   //统一设置发文自定义类型
    		}
    		else if("1".equals(edocType)){
    			iEdocType = EdocCustomConstant.REC_ADMIN;   //统一设置收文自定义类型
    		}
    	}
		return iEdocType;
	}
    
    /**
     * lijl添加,如果是用户选择意见覆盖方式,同一个公文单同一个人,在二条意见以上则弹出该文本框
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView optionSetup(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView("edoc/optionSetup");
    	String optionId=request.getParameter("optionId");
    	String optionType=request.getParameter("optionType");
    	String summaryIdStr=request.getParameter("summary_id");
    	Long summaryId=0L;
    	if(summaryIdStr!=null&&!"".equals(summaryIdStr)){
    		summaryId=Long.parseLong(summaryIdStr);
    	}
    	String policy=request.getParameter("policy");
    	modelAndView.addObject("summaryId",summaryId);
    	modelAndView.addObject("policy",policy);
    	modelAndView.addObject("optionId", optionId);
    	modelAndView.addObject("optionType", optionType);
    	return modelAndView;
    }
    /**
     * lijl添加,如果是用户选择意见覆盖方式,如果用户选择后修改State状态
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView upOptionState(HttpServletRequest request,
    		HttpServletResponse response) throws Exception {
    	response.setContentType("application/text;charset=UTF-8"); 
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
    	ModelAndView modelAndView = new ModelAndView("edoc/optionSetup");
    	String summaryIdStr=request.getParameter("summaryId");
    	String policy=request.getParameter("policy");
    	String optionType=request.getParameter("optionType");
    	String optionType1=request.getParameter("optionType1");
    	if("3".equals(optionType1)){
    		optionType1="1";
    	}else if("4".equals(optionType1)){
    		optionType1="2";
    	}
    	Long summaryId=0L;
    	if(summaryIdStr!=null&&!"".equals(summaryIdStr)){
    		summaryId=Long.parseLong(summaryIdStr);
    	}
    	User user=CurrentUser.get();
    	int state=0;
    	//3表示"退回时办理人选择意见覆盖方式,其他情况保留最后意见"
    	//4表示"退回时办理人选择意见覆盖方式,其他情况保留所有意见"
    	//state=1表示其他只显示最后一条信息,个人显示最后一条信息
    	if((optionType!=null)&&("3".equals(optionType))&&("1".equals(optionType1))){
	    	List<EdocOpinion> edocOpinionList=edocManager.findEdocOpinion(summaryId, user.getId(), policy);
	    	for(int i=0;i<edocOpinionList.size();i++){
	    		EdocOpinion edocOpinion=edocOpinionList.get(i);
	    		//修改状态
	    		edocOpinion.setState(1);
	    		edocManager.update(edocOpinion);
	    	}
	    	state=1;
    	}//state=2表示其他只显示最后一条信息,个人显示所有信息
    	else if((optionType!=null)&&("4".equals(optionType))&&("1".equals(optionType1))){
    		flag=true;//如果进入到此方法则设置flag为true表示[办理人选择的是"办理人选择覆盖方式,其他保留所有意见]
    		List<EdocOpinion> edocOpinionList=edocManager.findEdocOpinion(summaryId, user.getId(), policy);
	    	for(int i=0;i<edocOpinionList.size();i++){
	    		EdocOpinion edocOpinion=edocOpinionList.get(i);
	    		//修改状态
	    		edocOpinion.setState(0);
	    		edocManager.update(edocOpinion);
	    	}
	    	state=2;
    	}//state=3表示其他只显示所有信息,个人也只显示最后一条信息
    	else if((optionType!=null)&&("3".equals(optionType))&&("2".equals(optionType1))){
    		List<EdocOpinion> edocOpinionList=edocManager.findEdocOpinion(summaryId, user.getId(), policy);
	    	for(int i=0;i<edocOpinionList.size();i++){
	    		EdocOpinion edocOpinion=edocOpinionList.get(i);
	    		//修改状态
	    		edocOpinion.setState(1);
	    		edocManager.update(edocOpinion);
	    	}
	    	state=3;
    	}//state=4表示其他只显示所有信息,个人也显示所有信息
    	else if((optionType!=null)&&("4".equals(optionType))&&("2".equals(optionType1))){
    		//保留所有意见
    		List<EdocOpinion> edocOpinionList=edocManager.findEdocOpinion(summaryId, user.getId(), policy);
	    	for(int i=0;i<edocOpinionList.size();i++){
	    		EdocOpinion edocOpinion=edocOpinionList.get(i);
	    		//修改状态
	    		edocOpinion.setState(0);
	    		edocManager.update(edocOpinion);
	    	}
	    	state=4;
    	}
        pw.write(state); 
        pw.flush();
    	modelAndView.addObject("state",state);
    	return modelAndView;
    }
    /**
     * 保存勾选的自定义类别
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView saveCustomerTypes(HttpServletRequest request,
            HttpServletResponse response) throws Exception { 
    	String edocType=request.getParameter("edocType"); 
    	
    	String isAdminSet = request.getParameter("isAdminSet");
    	int iEdocType=-1;

    	//还要区分是待办还是已办
    	String from = request.getParameter("from");   
    	if(Strings.isNotBlank(from)){
    		iEdocType = getCustomType(edocType, from);
    	}
    	
    	
    	//选中的大的分类，比如 节点、时间、元素、自定义等
    	long bigTypeId = Long.parseLong(request.getParameter("bigTypeId"));
    	String[] typeIdStr = request.getParameterValues("typeId");
    	
    	
    	long[] typeIds = null;
    	String[] typeName = null;
    	String[] typeCode = null;
    	if(typeIdStr != null && typeIdStr.length > 0 ){
    		typeIds = new long[typeIdStr.length];
    		typeName = new String[typeIdStr.length];
        	typeCode = new String[typeIdStr.length];
        	
        	for(int i=0;i<typeIds.length;i++){
        		String[] nn = typeIdStr[i].split("_");
        		//流程节点 保存进 typeCode
        		if(bigTypeId == 0 || bigTypeId == 1){
        			typeCode[i] = nn[1];
        		}else{
        			typeName[i] = nn[1];
        		}
        		typeIds[i] = Long.parseLong(nn[0]);
        		typeName[i] = nn[1];
        		typeCode[i] = nn[2]+"_"+nn[3];
        		
        		
        	}  
    	} 
    	 
    	User user = this.getCurrentUser(); 
    	edocCustomerTypeManager.saveUserCustomerType(user,typeIds,typeName,typeCode,bigTypeId,iEdocType,isAdminSet,Integer.parseInt(edocType));
    	
    	ModelAndView modelAndView = new ModelAndView("edoc/inner");
    	modelAndView.addObject("message", "保存成功!");
    	return modelAndView; 	
    }
    
    /**
     * 已办结公文列表
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listFinish(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        String edocType=request.getParameter("edocType");
        String hasArchive=request.getParameter("hasArchive");
        int iEdocType=-1;
    	if(edocType!=null && !"".equals(edocType))
    	{
    		iEdocType=Integer.parseInt(edocType);
    	}
    	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        params.put("processType", 1);
    	ModelAndView modelAndView = new ModelAndView("edoc/listFinish");
    	int ihasArchive=-1;
    	if(hasArchive!=null && !"".equals(hasArchive)){
    		ihasArchive=Integer.parseInt(hasArchive);
    		modelAndView.addObject("ihasArchive", ihasArchive);
    	}
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());
        
        List<EdocSummaryModel> queryList = null;
        if (theMember.getAgentId() == -1) 
        {
            /**********组合查询组件调用开始*****************/
        	String comb_condition = request.getParameter("comb_condition");  //组合查询标识
            if(comb_condition!=null && "1".equals(comb_condition) ){
        		EdocSearchModel em=new EdocSearchModel();
        		bind(request, em);
        		//queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_done.key(),Constant.flowState.finish.ordinal(),ihasArchive);
        		queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_done.key(),params,new int[]{Constant.flowState.finish.ordinal(),ihasArchive});
        		modelAndView.addObject("combQueryObj", em);  //设置的查询条件还原到页面
        		modelAndView.addObject("combCondition", "1");
            }else
            /***************组合查询组件调用结束************/
        	if(condition != null) {
        		if(condition.equals("cusReceiveTime")){ //如果条件来自自定义分类的时间段，设置查询条件和查询起始时间
        			condition="receiveTime";
        			String[] textfield_condition= edocManager.getTimeTextFiledByTimeEnum(Integer.parseInt(textfield));
        			textfield=textfield_condition[0];
        			textfield1=textfield_condition[1];
        			
        		}
        		queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_done.key(), params, Constant.flowState.finish.ordinal(), ihasArchive);
        	}
        	if (queryList != null) {
        		modelAndView.addObject("pendingList", queryList);
        	} else {
        		List<EdocSummaryModel> finishedList = edocManager.queryByCondition(iEdocType,"", null, null,StateEnum.col_done.key(), params, Constant.flowState.finish.ordinal(), ihasArchive);
        		modelAndView.addObject("pendingList", finishedList);
        	}
        }
        else
        {
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }

        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
    
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
    	modelAndView.addObject("edocType", edocType);    	
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
    	}
    	else
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	int roleEdocType = iEdocType==1?3:iEdocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	boolean isArchiveRole=EdocRoleHelper.isEdocCreateRole(user.getAccountId(), user.getId(),EdocEnum.edocType.archiveModifyEdoc.ordinal());  //公文归档角色判断
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
    	modelAndView.addObject("isArchiveRole", isArchiveRole);
    	//发文拟文权限
    	boolean isSendEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
    	modelAndView.addObject("isSendEdocCreateRole", isSendEdocCreateRole);
        return modelAndView;
    }
    
    /**
     * 待办公文列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listPending(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    	request.getSession().removeAttribute("transmitSendAtts");    	
    	/*
    	List <V3xOrgMember> mems=EdocRoleHelper.getAccountExchangeUsers();
                                 HttpServletResponse response) throws Exception{
    	request.getSession().removeAttribute("transmitSendAtts");  
    	/* List <V3xOrgMember> mems=EdocRoleHelper.getAccountExchangeUsers();
    	System.out.println(mems.size());
    	List <V3xOrgMember> memsd=EdocRoleHelper.getDepartMentExchangeUsers();
    	System.out.println(memsd.size());
    	boolean isEdocAdmin=EdocRoleHelper.isAccountExchange();
    	isEdocAdmin=EdocRoleHelper.isDepartmentExchange();    	
    	String ids=EdocRoleHelper.getUserExchangeDepartmentIds();
    	System.out.println("department ids="+ids);*/

        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        String edocType=request.getParameter("edocType");
        String list=request.getParameter("list");//区分待办、在办 
        //GOV-3428 公文管理-收文管理-待办页面，进入页面后默认显示待办公文，不正确
        //默认进入待办的 全部
        if(Strings.isBlank(list)){
        	list = "listPending";
        }
        
    	int iEdocType=-1;
     	if(edocType!=null && !"".equals(edocType))
    	{
    		iEdocType=Integer.parseInt(edocType);
    	}
     	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        params.put("processType", 1);
        ModelAndView modelAndView = new ModelAndView("edoc/listPending");
        
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId()); 
         
        List<EdocSummaryModel> queryList = null;
        if (theMember.getAgentId() == -1){ 
            /**********组合查询组件调用开始*****************/
        	String comb_condition = request.getParameter("comb_condition");  //组合查询标识
            if(comb_condition!=null && "1".equals(comb_condition) ){
        		EdocSearchModel em=new EdocSearchModel();
        		bind(request, em);
        		params.put("list", list);
//        		queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_pending.key());
        		queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_pending.key(),params,new int[]{});
        		modelAndView.addObject("combQueryObj", em);  //设置的查询条件还原到页面
        		modelAndView.addObject("combCondition", "1");
            }else
            /***************组合查询组件调用结束************/
        	if(condition != null && !"".equals(condition)) {     
        		if(condition.equals("cusReceiveTime")){ //如果条件来自自定义分类的时间段，设置查询条件和查询起始时间
        			condition="receiveTime";
        			String[] textfield_condition= edocManager.getTimeTextFiledByTimeEnum(Integer.parseInt(textfield));
        			textfield=textfield_condition[0];
        			textfield1=textfield_condition[1];
        		}
        		
//        		queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_pending.key(), params, -1,-1,1);
        		//修复bug GOV-3085 【公文管理】-【发文管理】-【待办】，发文待办【全部】列表里有16条记录，
        		//但是根据任一查询条件只能查询出14条待办状态的，在办状态的查询不到
        		if(null !=list &&  list.equals("notPending") ){
        			queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_pending.key(),params,-1,-1,1);
        		}else{
        			queryList = edocManager.queryByCondition(iEdocType, condition, textfield, textfield1, StateEnum.col_pending.key(),params); //全部待办数据
        		}
        		
        	}
        	if (queryList != null) { 
        		modelAndView.addObject("pendingList", queryList);
        	} else {
        		if("".equals(condition) || null==condition) {
        			List<EdocSummaryModel> pendingList = null;
        			if(iEdocType==1){
        				params.put("processType", 1);
        				if(null !=list && list.equals("pending")){
        					pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params, 1,-1,1); //查询已办数据
        				}
        				if(null !=list && list.equals("listPending")){//全部
        					pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params);
        				}
        				else{
        					pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params, -1,-1,1); //全部待办数据
        				}
        			}else{ 
        				if(null !=list && list.equals("notPending")){//发文，待办（不包括在办）
        					pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params, -1); 
        				}
        				else{//全部待办数据
        					pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params); //页签，全部待办数据
        				}
        				
        			}
        		   modelAndView.addObject("pendingList", pendingList);
        		}else{
        			List<EdocSummaryModel> pendingList = null;
        			if(null !=list && list.equals("notPending")){
        				pendingList = edocManager. queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params, -1,-1,1);//左侧列表，除去在办数据
        			}else{
        				pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params); //全部待办数据
        			}
         		   
        		   modelAndView.addObject("pendingList", pendingList);
        		}
        	}
        }
        else
        {
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }
 
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);           
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        
        /*
         * 元数据中加载 秘密程度
         * cy add
         */
        Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        colMetadata.put(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);

        
        
        /*
         * 元数据中加载 紧急程度
         * cy add
         */
        Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        colMetadata.put(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);
    	
        //是否包含“待登记”按钮
    	boolean hasRegistButton=false;
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
    		hasRegistButton=true;
    	}
    	else
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	modelAndView.addObject("hasRegistButton", hasRegistButton);
    	/*********转发文**********/
    	modelAndView.addObject("newForwardaRrticle","edoc.new.type.forwardarticle");
    	/*********转发文**********/
    	int roleEdocType = iEdocType==1?3:iEdocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
    	//发文的拟文权限
    	boolean isSendEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
    	modelAndView.addObject("isSendEdocCreateRole", isSendEdocCreateRole);
    	
        return modelAndView;
    }
    /**
     * 弹出公文转起草类型提示框
     * wangwei
     */
    public ModelAndView forwordOption(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	 ModelAndView modelAndView = new ModelAndView("edoc/forwordOption");
        return modelAndView;
    }
    /**
     * 弹出阅文批处理分发页面
     */
    public ModelAndView readBatchWD(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	    ModelAndView modelAndView = new ModelAndView("edoc/edocReadBatch");
	    	String defaultPerm="yuedu";
	    	modelAndView.addObject("defaultPermLabel", "node.policy."+defaultPerm); 
	        return modelAndView;
    }
    
    /**
     * 公文督办查询---魏俊标
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listEdocSuperviseController(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView("edoc/listSupervise");
//        User user = this.getCurrentUser();
        int edocType = request.getParameter("edocType")==null? 0 : Integer.parseInt(request.getParameter("edocType"));
        //是否包含“待登记”按钮        
//        boolean hasRegistButton=false;
//        if(EdocEnum.edocType.recEdoc.ordinal()==edocType) {//收文
//            modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
//            hasRegistButton = true;
//        } else  {
//            modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
//        }
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);
//        modelAndView.addObject("hasRegistButton", hasRegistButton);
        //公文发起权与公文交换权
//        boolean isEdocCreateRole = EdocRoleHelper.isEdocCreateRole(edocType);
//        boolean isExchangeRole = EdocRoleHelper.isExchangeRole(); 
//        modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
//        modelAndView.addObject("isExchangeRole", isExchangeRole);
        //收文登记与分发权限
//        boolean isEdocCreateRegister = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.recEdoc.ordinal());
//        boolean isEdocDistribute = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.distributeEdoc.ordinal());
//        modelAndView.addObject("isEdocCreateRegister", isEdocCreateRegister);
//        modelAndView.addObject("isEdocDistribute", isEdocDistribute);
        return modelAndView;
    }
    /**
     * 在办公文列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listZcdb(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    	request.getSession().removeAttribute("transmitSendAtts");    	
    	/*    	 
    	List <V3xOrgMember> mems=EdocRoleHelper.getAccountExchangeUsers();
    	System.out.println(mems.size());
    	
    	List <V3xOrgMember> memsd=EdocRoleHelper.getDepartMentExchangeUsers();
    	System.out.println(memsd.size());
    	boolean isEdocAdmin=EdocRoleHelper.isAccountExchange();
    	isEdocAdmin=EdocRoleHelper.isDepartmentExchange();    	
    	String ids=EdocRoleHelper.getUserExchangeDepartmentIds();
    	System.out.println("department ids="+ids);
    	*/
    	
    	
        String condition = request.getParameter("condition");
        
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        
        String edocType=request.getParameter("edocType");
    	int iEdocType=-1;
    	if(edocType!=null && !"".equals(edocType))
    	{
    		iEdocType=Integer.parseInt(edocType);
    	}
    	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        //GOV-4012 收文管理-待阅，暂存待办事项后，从待阅列表消失，跑到待办-在办列表中了
        //changyi 收文在办，需要加上待办的类型
        if("1".equals(edocType)){
        	params.put("processType", 1);
        }
        
        ModelAndView modelAndView = new ModelAndView("edoc/listZcdb");
        
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());
        
        /***************测试代码开始*****************/
        //Long metadataId=7971699406983548687L;
        //edocManager.useMetadataValue(user.getLoginAccount(),metadataId,"22");
        /***************测试代码结束*****************/
        
        List<EdocSummaryModel> queryList = null;
        if (theMember.getAgentId() == -1){
            /**********组合查询组件调用开始*****************/
        	String comb_condition = request.getParameter("comb_condition");  //组合查询标识
            if(comb_condition!=null && "1".equals(comb_condition) ){
        		EdocSearchModel em=new EdocSearchModel();
        		bind(request, em);
        		queryList = edocManager.combQueryByCondition(iEdocType,em,StateEnum.col_pending.key(),SubStateEnum.col_pending_ZCDB.getKey());
        		modelAndView.addObject("combQueryObj", em);  //设置的查询条件还原到页面
        		modelAndView.addObject("combCondition", "1");
            }else
            /***************组合查询组件调用结束************/
            if(condition != null) {
        		if(condition.equals("cusReceiveTime")){ //如果条件来自自定义分类的时间段，设置查询条件和查询起始时间
        			condition="receiveTime";
        			String[] textfield_condition= edocManager.getTimeTextFiledByTimeEnum(Integer.parseInt(textfield));
        			textfield=textfield_condition[0];
        			textfield1=textfield_condition[1];
        			
        		}
        		queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_pending.key(), params, SubStateEnum.col_pending_ZCDB.getKey());
        	}
            
        	if (queryList != null) {
        		modelAndView.addObject("pendingList", queryList);
        	} else {
        		List<EdocSummaryModel> pendingList = edocManager.queryByCondition(iEdocType,"", null, null, StateEnum.col_pending.key(), params, SubStateEnum.col_pending_ZCDB.getKey());;
        		modelAndView.addObject("pendingList", pendingList);
        	}
        }
        else
        {
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }

        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);           
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);
    	
        //是否包含“待登记”按钮
    	boolean hasRegistButton=false;
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
    		hasRegistButton=true;
    	}
    	else
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	modelAndView.addObject("hasRegistButton", hasRegistButton);
    	int roleEdocType = iEdocType==1?3:iEdocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
        return modelAndView;
    }
    
    
    /**
     * 待办登记公文列表
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listRegisterPending(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        //String condition = request.getParameter("condition");
        //String textfield = request.getParameter("textfield");
        //String textfield1 = request.getParameter("textfield1");
    	   
    	User user = CurrentUser.get();    	
    	Long userId=user.getId();        
        ModelAndView mav = new ModelAndView("edoc/listRegisterPending");        
        List<EdocRecieveRecord> list = recieveEdocManager.getWaitRegisterEdocRecieveRecords(userId);
		if(list != null)
			for(EdocRecieveRecord r : list){
				EdocSummary summary = edocSummaryManager.findById(r.getEdocId());
				r.setCopies(summary==null?0:summary.getCopies());
			}
        	
        mav.addObject("edocType", EdocEnum.edocType.recEdoc.ordinal()); 
        mav.addObject("controller", "edocController.do");
        mav.addObject("newEdoclabel", "edoc.new.type.rec");
        
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
        
        mav.addObject("colMetadata", colMetadata);
		mav.addObject("list", pagenate(list));        
        return mav;
    }
  
	private <T> List<T> pagenate(List<T> list) {
		if (null == list || list.size() == 0)
			return new ArrayList<T>();
		Integer first = Pagination.getFirstResult();
		Integer pageSize = Pagination.getMaxResults();
		Pagination.setRowCount(list.size());
		List<T> subList = null;
		if (first + pageSize > list.size()) {
			subList = list.subList(first, list.size());
		} else {
			subList = list.subList(first, first + pageSize);
		}
		return subList;
	}   
    
    /**
     * 已发公文列表
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listSent(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        long subEdocType = Strings.isBlank(request.getParameter("subType"))?-1:Long.parseLong(request.getParameter("subType"));
        String edocType=request.getParameter("edocType");    	
    	int iEdocType=-1;
    	if(edocType!=null && !"".equals(edocType))
    	{
    		iEdocType=Integer.parseInt(edocType);
    	}
    	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        ModelAndView modelAndView = new ModelAndView("edoc/listSent");
        
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());
        //时间分类查询（本日，昨日，本周等）
		String listType=request.getParameter("listType");
		int listTypeInt=0; 
		if(listType!=null && !"".equals(listType)){
			listTypeInt=Integer.parseInt(listType);
			condition="createDate"; //收文的创建时间createDate
			String[] dateFields=com.seeyon.v3x.edoc.util.DateUtil.getTimeTextFiledByTimeEnum(listTypeInt);
			textfield=dateFields[0];
			textfield1=dateFields[1];
		}
        List<EdocSummaryModel> queryList = null;   
        if (theMember.getAgentId() == -1)
        {
        	if(condition != null) {        
        		queryList = edocManager.queryByCondition1(iEdocType,condition, textfield, textfield1, subEdocType, StateEnum.col_sent.key(), params);
        	}
        	if (queryList != null) {
        		modelAndView.addObject("pendingList", queryList);
        	} else {
        		List<EdocSummaryModel> finishedList = edocManager.querySentList(iEdocType, subEdocType, params);
        		modelAndView.addObject("pendingList", finishedList);
        	}
        } 
        else
        {
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }
        
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
        
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        
        /*
         * 元数据中加载 秘密程度
         * cy add
         */
        Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        colMetadata.put(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);
        
        /*
         * 元数据中加载 紧急程度
         * cy add
         */
        Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        colMetadata.put(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
        
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);        
        
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.element.receive.distribute");
    	}
    	else
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	int roleEdocType = iEdocType==1?3:iEdocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
    	
    	//发文的拟文权限
    	boolean isSendEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
    	modelAndView.addObject("isSendEdocCreateRole", isSendEdocCreateRole);
    	
        return modelAndView;
    }
    /**
     * 公文草稿箱/退件箱/退稿箱
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView listWaitSend(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1"); 
        //String subStateStr = request.getParameter("subState");
        long subEdocType = Strings.isBlank(request.getParameter("subType"))?-1:Long.parseLong(request.getParameter("subType"));
        String edocType=request.getParameter("edocType");    
        String list = request.getParameter("list");
    	int iEdocType = Strings.isBlank(request.getParameter("edocType")) ? -1 : Integer.parseInt(request.getParameter("edocType")); 
    	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        ModelAndView modelAndView; 
        if("backBox".equals(list) || "retreat".equals(list)) {//backBox发文退稿箱,retreat收文退件箱
        	modelAndView = new ModelAndView("edoc/listBackBox");//跳转到退稿想
		} else {
			modelAndView = new ModelAndView("edoc/listWaitSend");//跳转到草稿箱
		}
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());      
        
        List<EdocSummaryModel> queryList = null;
        if (theMember.getAgentId() == -1) {//无代理人 
        	//1：退件箱2：草稿箱，收文、发文一样
        	int type = -1;
        	if("draftBox".equals(list)) {//草稿箱
        		type = 2;
        	} else if("backBox".equals(list) || "retreat".equals(list)) { //backBox发文退稿箱,retreat收文退件箱
        		type = 1;
        	} 
        	if(condition != null && Strings.isNotBlank(textfield)) {//判断查询条件是否为空
        		int sub_state= 0;//默认显示原来的状态
        		if(("backBox".equals(list) && "backBox".equals(condition))||"retreat".equals(list) && "retreat".equals(condition) ){//获取退回方式状态 
        			String s_State=request.getParameter("textfield");
        			if(Strings.isNotBlank(s_State)){//判断是否为空 
        				sub_state=Integer.parseInt(s_State);//转换
        			}
        		}
        		if(sub_state !=0 ) {
        			queryList = edocManager.queryByCondition1(iEdocType,condition, textfield, textfield1,  subEdocType, StateEnum.col_waitSend.key(), params, sub_state);        	
        		} else {
        			queryList = edocManager.queryByCondition1(iEdocType,condition, textfield, textfield1,  subEdocType, StateEnum.col_waitSend.key(), params, -1,-1,1,type);
        		}
        	}
        	if (queryList != null) {
        		modelAndView.addObject("pendingList", queryList);
        	} else {
        		modelAndView.addObject("equal", type);
        		List<EdocSummaryModel> finishedList = edocManager.queryDraftList(iEdocType, subEdocType, params, -1,-1,1,type);
        		modelAndView.addObject("pendingList", finishedList);
        	}
        } else {//有代理人
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }
       
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
        
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        
        /*
         * 元数据中加载 秘密程度
         * cy add
         */
        Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        colMetadata.put(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);
        
        /*
         * 元数据中加载 紧急程度
         * cy add
         */
        Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        colMetadata.put(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);        
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType) {
    		modelAndView.addObject("newEdoclabel", "edoc.element.receive.distribute");
    	} else {
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	int roleEdocType = iEdocType==1?3:iEdocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
        return modelAndView;
    }
    public ModelAndView listIndex(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView("edoc/listIndex");
        //会议纪要转公文 获得会议纪要ID
        String meetingSummaryId = request.getParameter("meetingSummaryId");
        User user = this.getCurrentUser();
        int edocType = request.getParameter("edocType")==null? 0 : Integer.parseInt(request.getParameter("edocType"));
        //是否包含“待登记”按钮        
        boolean hasRegistButton=false;
        if(EdocEnum.edocType.recEdoc.ordinal()==edocType) {//收文
            modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
            hasRegistButton = true; 
        } else {
            modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
        }
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);
        modelAndView.addObject("hasRegistButton", hasRegistButton);
        //公文发起权与公文交换权
        int roleEdocType = edocType==1?3:edocType;
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(roleEdocType);
        boolean isExchangeRole = EdocRoleHelper.isExchangeRole(); 
        modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
        modelAndView.addObject("isExchangeRole", isExchangeRole);
        //收文登记与分发权限
        boolean isEdocCreateRegister = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.recEdoc.ordinal());
        boolean isEdocDistribute = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.distributeEdoc.ordinal());
        modelAndView.addObject("isEdocCreateRegister", isEdocCreateRegister);
        modelAndView.addObject("isEdocDistribute", isEdocDistribute);
        modelAndView.addObject("meetingSummaryId", meetingSummaryId);
        
        return modelAndView;
    }
    public ModelAndView listLeft(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView("edoc/listLeft");
//        int edocType = request.getParameter("edocType")==null? 0 : Integer.parseInt(request.getParameter("edocType"));
        User user = this.getCurrentUser();
    	//获取单位ID 
    	//根据发文或收文，获取其节点权限列表
    	//获得当前是 发文还是收文
    	
    	String from = request.getParameter("from");
    	String edocType = request.getParameter("edocType");
    	int etype = Integer.parseInt(edocType);
    	int iEdocType = -1;
    	if("listPending".equals(from)){
    		if("0".equals(edocType)){
    			iEdocType = 1;	//发文待办
    		}else{
    			iEdocType = 3;	//收文待办
    		}
    	}else if("listDone".equals(from)){
    		if("0".equals(edocType)){
    			iEdocType = 2;	//发文已办
    		}else{
    			iEdocType = 4;	//收文已办
    		}
    	}else if("listReaded".equals(from)){	//已阅
    		iEdocType = 5;
    	}
    	
    	modelAndView.addObject("edocType", etype);
    	
    	//用户已勾选 需要显示的 类别列表
		Map map = edocCustomerTypeManager.getUserCustomerTypeList(user, iEdocType,null,Integer.parseInt(edocType));
		List<EdocCustomerType> customerTypeList = (List<EdocCustomerType>)map.get("customerTypeList");
		List<EdocCustomerType> customerTypeList_new = new ArrayList<EdocCustomerType>();
		//查询条件的set
		if(customerTypeList!=null && customerTypeList.size()>0){
			for(EdocCustomerType edocCustomerType : customerTypeList){
				String typeCode=edocCustomerType.getTypeCode();
				String[] conditionArray=typeCode.split("_");
				String condition=conditionArray[0];
				String conditionvalue=conditionArray[1];
				edocCustomerType.setCondition(condition);
				edocCustomerType.setTextfield(conditionvalue);
				//公文元素名称（紧急程度，密级等）
				if(edocCustomerType.getBigTypeId()==4){
					if(condition.equals("urgentLevel")){
						edocCustomerType.setEdocElementLabel("edoc.element.urgentlevel");
					}else if(condition.equals("secretLevel")){
						edocCustomerType.setEdocElementLabel("edoc.element.secretlevel");
					}else if(condition.equals("sendType")){
						edocCustomerType.setEdocElementLabel("edoc.element.sendtype");
					}
				}
				customerTypeList_new.add(edocCustomerType);
			}
		}
		List<EdocCategory> edocCategoryList = edocCategoryManager.getCategoryByAccount(user.getLoginAccount());
		modelAndView.addObject("edocCategoryList", edocCategoryList);
		modelAndView.addObject("customerTypeList", customerTypeList_new);
		modelAndView.addObject("isEdocAdmin", EdocRoleHelper.isAccountEdocAdmin());
		//发文草稿箱标志  subState=1
		modelAndView.addObject("sendBackState", SubStateEnum.col_waitSend_draft.getKey());
		//收文退稿箱标志，目前收文待发分为草稿箱和退件箱，退件箱的subState=4
		modelAndView.addObject("stepBackState", SubStateEnum.col_waitSend_stepBack.getKey());
	 	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(etype);
	 	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);

		
        return modelAndView;
    } 
    /** 发送登记单显示请求-唐4桂林2011-10-12 */
    public ModelAndView edocRegisterDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {        
        try { 
        	ModelAndView modelAndView = new ModelAndView("edoc/edocRegisterDetail");
        	Long registerId = null;
        	if(!Strings.isBlank(request.getParameter("registerId"))){
        		registerId = Long.parseLong(request.getParameter("registerId"));
        	}
        	if(registerId == null){
                String msg = "已没有";
                throw new ColException(msg);
            }        	
        	String list = request.getParameter("list");
        	if(!Strings.isNotBlank(list)){
        		list = "popup";
        	}
        	//有可能公文已经处理完了，但是消息提示框仍然在哪里，所以需要重新查询一下当前事项的状态。
        	String from = request.getParameter("from");
        	modelAndView.addObject("registerId", registerId);
        	modelAndView.addObject("list", list);
        	modelAndView.addObject("from", from);
        	modelAndView.addObject("controller", "edocController.do");
        	return modelAndView;
        } catch (Exception e) {
        	PrintWriter out = response.getWriter();        	
        	out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(e.getMessage()) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"true\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("");
        	out.println("</script>");
        	return null;
		}
    }
    
    /** 显示登记单信息，包括附件和正文及登记单-唐桂林2011-10-12 */
    public ModelAndView edocRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try { 
        	ModelAndView modelAndView = new ModelAndView("edoc/edocRegister");
        	long registerId = request.getParameter("registerId")==null? -1L : Long.parseLong(request.getParameter("registerId"));
         	EdocRegister edocRegister = edocRegisterManager.getEdocRegister(registerId);
        	
        	//已登记和待分发，关联发文id都用登记id
        	long relationId = registerId;
//        	if(edocRegister.getRegisterType()==1){
//        		relationId = edocRegister.getEdocId();
//        	}
        	int forward = 0;
        	String forwardType = request.getParameter("forwardType");
        	if("registered".equals(forwardType)){
        		forward = 1;
        	}else if("waitSent".equals(forwardType)){
        		forward = 2;
        	}
        	
        	User user = CurrentUser.get();
        	/********* 关联发文 * 收文的Id,收文的Type*********/
            String relSends = "haveNot";  
            String relRecs = "haveNot";
//            List<EdocSummary> newEdocList = this.edocSummaryRelationManager.findNewEdoc(registerId, user.getId(), 1);
            List<EdocSummary> newEdocList = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(relationId, user.getId(), 1,forward);//已登记
            //如果已登记下还没有关联发文，需要获得待登记下关联的发文 (需要在已登记列表查看时，待分发就不用了)
            if(newEdocList == null && forward == 1){
            	//获得签收id,如果是纸质公文就不用了
            	long recieveId = edocRegister.getRecieveId();
            	if(recieveId != -1){
            		newEdocList = this.edocSummaryRelationManager.findNewEdoc(recieveId, user.getId(), 1);
            	}
            }
            
            
            if(newEdocList != null){
            	 relSends = "haveMany";
//            	 modelAndView.addObject("recEdocId",registerId);
            	 modelAndView.addObject("recEdocId",relationId);
                 modelAndView.addObject("recType",1);
                 modelAndView.addObject("relSends",relSends);
            } 
            /********* 关联 发文的Id 发文的Type**********/
        	
        	RegisterBody registerBody = edocRegisterManager.findRegisterBodyByRegisterId(registerId);
        	modelAndView.addObject("edocType", edocRegister.getEdocType());
        	modelAndView.addObject("controller", "edocController.do");
        	//是否允许拟文人修改附件。
        	boolean allowUpdateAttachment = EdocSwitchHelper.allowUpdateAttachment();
            modelAndView.addObject("allowUpdateAttachment", allowUpdateAttachment);            
            modelAndView.addObject("firstPDFId", registerBody!=null ? registerBody.getContent() : "");
            //只查找正文的附件。
            modelAndView.addObject("attachments", attachmentManager.getByReference(registerId, registerId));  
        	modelAndView.addObject("bean", edocRegister);
        	modelAndView.addObject("registerBody", registerBody);
        	modelAndView.addObject("curUser", CurrentUser.get());
        	if(registerBody!=null) {
        		if(registerBody.getCreateTime()==null) {
        			registerBody.setCreateTime(edocRegister.getCreateTime());
        			registerBodyManager.updateReigsterBody(registerBody);
        		}
        	}
        	StringBuffer contentBuffer = registerBodyManager.getRegisterContent(request, registerBody);
        	modelAndView.addObject("content", contentBuffer.toString());
        	return modelAndView;
        } catch (Exception e) {
        	log.error("",e);
        	PrintWriter out = response.getWriter();    	
        	out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(e.getMessage()) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"true\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("");
        	out.println("</script>");
        	return null;
		}
    }
    
    /** 显示登记单-唐桂林2011-10-12 */
    public ModelAndView edocRegisterFormDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	try {  
        	User user = CurrentUser.get(); 
        	ModelAndView mav = new ModelAndView("edoc/edocRegisterFormDetail");
        	long registerId = request.getParameter("registerId")==null? -1L : Long.parseLong(request.getParameter("registerId"));
        	EdocRegister edocRegister = edocRegisterManager.getEdocRegister(registerId);
        	
        	/********* puyc 关联发文 * 收文的Id,收文的Type *********/
			String relSends = "haveNot";
			List<EdocSummary> newEdocList = this.edocSummaryRelationManager
					.findNewEdoc(edocRegister.getEdocId(), user.getId(), 1);
			if (newEdocList != null) {
				relSends = "haveMany";
				mav.addObject("recEdocId", edocRegister.getEdocId());
				mav.addObject("recType", 1);
				mav.addObject("relSends", relSends);

			}
			/*********** puyc end ************/
			
        	//lijl添加,修改bug 40928(登记时收文编号与手工录入的编号不一致)-----------------------------Start
        	if(edocRegister!=null&&!"".equals(edocRegister)){
        		String serialNo=edocRegister.getSerialNo();
        		if(serialNo!=null&&!"".equals(serialNo)){
        			try{
        				String str=serialNo.substring(serialNo.indexOf("|")+1,serialNo.indexOf("||"));
        				edocRegister.setSerialNo(str);
        			}catch(Exception ex){
        				edocRegister.setSerialNo(serialNo);
        			}
        		}
        	}
        	//lijl添加,修改bug 40928(登记时收文编号与手工录入的编号不一致)-----------------------------End
            mav.addObject("bean", edocRegister);
            mav.addObject("controller", "edocController.do");
            RegisterBody body = edocRegister.getRegisterBody();
        	mav.addObject("edocType", edocRegister.getEdocType());
        	mav.addObject("curUser", CurrentUser.get());
        	Metadata sendUnitTypeData = metadataManager.getMetadata(MetadataNameEnum.send_unit_type);//来文类别
            Metadata edocSecretLevelData = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);//密级程度
            Metadata edocUrgentLevelData = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);//紧急程度
            Metadata edocKeepPeriodData = metadataManager.getMetadata(MetadataNameEnum.edoc_keep_period);//保密期限

            List<EdocMarkModel> serialNoList = edocMarkDefinitionManager.getEdocMarkDefinitions(user.getDepartmentId()+","+user.getAccountId(), 1);
            mav.addObject("sendUnitTypeData", sendUnitTypeData);
            mav.addObject("edocSecretLevelData", edocSecretLevelData);
            mav.addObject("edocUrgentLevelData", edocUrgentLevelData);
            mav.addObject("edocKeepPeriodData", edocKeepPeriodData);
            mav.addObject("serialNoList", serialNoList);
        	return mav;
        } catch (Exception e) {
        	log.error("",e);
        	PrintWriter out = response.getWriter();    	
        	out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(e.getMessage()) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"true\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("");
        	out.println("</script>");
        	return null;
		}
    
    }

    /** 显示登记单-唐桂林2011-10-12 */
    public ModelAndView selectDistributer(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get(); 
    	ModelAndView mav = new ModelAndView("edoc/selectDistributer");
        mav.addObject("controller", "edocController.do");
        mav.addObject("curUser", user);
    	return mav;       
    }
    
    /** 批处理-唐桂林2011-10-12 */
    public ModelAndView batchRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get(); 
    	String registerType = request.getParameter("registerType");
    	long distributerId = request.getParameter("distributerId")==null? user.getId() : Long.parseLong(request.getParameter("distributerId"));
    	String distributer = request.getParameter("distributer")==null? user.getName() : request.getParameter("distributer");
    	String[] recieveIds = request.getParameterValues("recieveId");
    	RegisterBody registerBody = null;
    	EdocRegister edocRegister = null;
    	EdocRecieveRecord edocRecieveRecord = null;
    	EdocSummary summary = null;
    	EdocBody edocBody = null;
    	if(recieveIds!=null) {
    		for(int i=0; i<recieveIds.length; i++) {
    			edocRegister = new EdocRegister();
    			//来文信息
    	        long recieveId = Long.parseLong(recieveIds[i]);
    			edocRecieveRecord = recieveEdocManager.getEdocRecieveRecord(recieveId);
    	        if(edocRecieveRecord==null) {
    	        	return null;
    	        }
    	        edocRegister.setEdocId(edocRecieveRecord.getEdocId());
    	        edocRegister.setRecieveId(recieveId);
        		//装载数据到登记表
    	        edocRegister.setNewId();
    	        edocRegister.setCreateUserId(user.getId());
    	        edocRegister.setCreateUserName(user.getName());
    	        edocRegister.setCreateTime(new java.sql.Timestamp(new Date().getTime()));
    	        edocRegister.setUpdateTime(new java.sql.Timestamp(new Date().getTime()));
    	        edocRegister.setOrgAccountId(user.getAccountId());
    	        edocRegister.setState(EdocNavigationEnum.RegisterState.Registed.ordinal());
    	        //设置登记人
    	        edocRegister.setRegisterUserId(user.getId());
    	        edocRegister.setRegisterUserName(user.getName());
    	        //设置默认分发人        
    	        edocRegister.setDistributerId(distributerId);
    	        edocRegister.setDistributer(distributer);
    	        edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.WaitDistribute.ordinal());
    	        edocRegister.setRegisterType(Integer.parseInt(registerType));
    	        edocRegister.setRegisterDate(new java.sql.Date(new Date().getTime()));    	        
    	        V3xOrgAccount account = orgManager.getAccountById(user.getLoginAccount());
    	        edocRegister.setSendUnit(account==null?"":account.getName());
    	        edocRegister.setSendUnitId(1);
    	        edocRegister.setSendUnitType(edocRecieveRecord==null? 1 : edocRecieveRecord.getSendUnitType());
    	        edocRegister.setEdocType(EdocEnum.edocType.recEdoc.ordinal());
    	        
    	        summary = edocManager.getEdocSummaryById(edocRecieveRecord.getEdocId(), true);
    	        
    	        edocRegister.setDocType(edocRecieveRecord.getDocType());
    	        edocRegister.setSubject(edocRecieveRecord.getSubject());
    	        edocRegister.setDocMark(edocRecieveRecord.getDocMark());
    	        edocRegister.setSecretLevel(edocRecieveRecord.getSecretLevel());
    	        edocRegister.setUrgentLevel(edocRecieveRecord.getUrgentLevel());
    	        //公文元素基本信息
    	        edocRegister.setSerialNo(null);
    	        edocRegister.setIdentifier("00000000000000000000");
    	        edocRegister.setKeepPeriod(summary==null? "" : String.valueOf(summary.getKeepPeriod()));
    	        edocRegister.setSendType(summary==null? "1" : summary.getSendType());
    	        edocRegister.setKeywords(summary==null? "" : summary.getKeywords());
    	        edocRegister.setIssuerId(-1);
    	        edocRegister.setIssuer(summary==null? "" : summary.getIssuer());
    	        edocRegister.setEdocDate(summary==null? null : summary.getSigningDate());
    	        if(edocRegister.getEdocDate()==null) {//如果没有签发时间，则显示为封发时间
    	            edocRegister.setEdocDate(summary==null ? null : new java.sql.Date(summary.getPackTime().getTime()));
    	        }
    	        //附件信息
    	        List<Attachment> attachmentList = null;
    	        //装载公文正文
    	        if(summary !=null && edocRecieveRecord!=null) {    	        	
    	        	edocBody = summary.getBody(edocRecieveRecord.getContentNo().intValue());
    	        	registerBody = new RegisterBody();
    	        	edocBody = edocBody==null?summary.getFirstBody() : edocBody;
    				if(null != edocBody){
    					if("HTML".equals(edocBody.getContentType())) {
    						registerBody.setContent(edocBody.getContent());
        					registerBody.setContentNo(edocBody.getContentNo());
        					registerBody.setContentType(edocBody.getContentType());
    					} else {
    						registerBody.setContent(Long.toString(UUIDLong.longUUID()));
	    					registerBody.setContentType(edocBody.getContentType());
	    					registerBody.setCreateTime(new java.sql.Timestamp(new Date().getTime()));
    					}
    					registerBody.setIdIfNew();
    				} 
    				//增加正文文件和v3x_file
        	        try {
    					if(!"HTML".equals(edocBody.getContentType())) {
    						//复制正文及复制v3x_file表数据
    						V3XFile file = fileManager.clone(Long.parseLong(edocBody.getContent()), true);
    						file.setFilename(file.getId().toString());
    						fileManager.update(file);
    						registerBody.setContent(file.getId().toString());
    						//复制印章什么的？
    					}
    					//增加附件
        				this.attachmentManager.copy(summary.getId(), summary.getId(), edocRegister.getId(), edocRegister.getId(), ApplicationCategoryEnum.edocRegister.ordinal());//附件
        				attachmentList = attachmentManager.getByReference(edocRegister.getId(), edocRegister.getId());
        				/*for(int k=0; k<attachmentList.size(); k++) {
        					fileManager.clone(attachmentList.get(k).getFileUrl(), attachmentList.get(k).getCreatedate(), edocRegister.getId(), new java.util.Date());
        				}*/
        	    	    edocRegister.setHasAttachments(attachmentList.size()>0);
    				} catch(Exception e) {
    					e.printStackTrace();
    				}
    				
    	        }
    	        if(summary!=null && !Strings.isBlank(summary.getSendUnit()) && !Strings.isBlank(summary.getSendUnitId())) {
    	            edocRegister.setEdocUnit(summary.getSendUnit());
    	            edocRegister.setEdocUnitId(summary.getSendUnitId());
    	        }
    	        registerBody.setEdocRegister(edocRegister);
    	        edocRegister.setRegisterBody(registerBody);
    	        edocRegisterManager.createEdocRegister(edocRegister);
    	        
    	        
    	        
    	        //修改签收单
    	        edocRecieveRecord.setRegisterUserId(edocRegister.getRegisterUserId());
    	        edocRecieveRecord.setRegisterTime(new java.sql.Timestamp(edocRegister.getRegisterDate().getTime()));
    	        edocRecieveRecord.setRegisterName(edocRegister.getRegisterUserName());
    	        edocRecieveRecord.setStatus(com.seeyon.v3x.exchange.util.Constants.C_iStatus_Registered);
    	        recieveEdocManager.update(edocRecieveRecord);
    	        if(edocRegister.getState() == 2) {
    	        	//去掉待登记
    	        	Map<String, Object> params = new HashMap<String, Object>();
    	        	params.put("app", ApplicationCategoryEnum.edocRegister.getKey());
    	        	params.put("objectId", edocRecieveRecord.getEdocId());
    		        List<Affair> affairList = affairManager.getByConditions(params);
    		        if(affairList!=null) {
    		        	for(int j=0; j<affairList.size(); j++) {
    		        		affairList.get(j).setState(StateEnum.edoc_exchange_registered.getKey());
    		        		affairManager.updateAffair(affairList.get(j));
    		        	}
    		        }
    	        }
    	        
    	        //发送消息
    	        if(edocRegister.getState() == 2) {
    	        	sendMessageToRegister(user, -1, edocRegister, "create", -1);	
    	        }
        	}
    	}
    	
    	String listType = request.getParameter("listType");
    	return super.redirectModelAndView("/edocController.do?method=listRegister&listType="+listType+"&from=listRegister&edocType=" + edocRegister.getEdocType());
    }
    
    /** 登记列表  --唐桂林20110923 */
    public ModelAndView listRegister(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	ModelAndView mav = new ModelAndView("edoc/listRegister");   
    	User user = CurrentUser.get(); 
    	int edocType = request.getParameter("edocType")==null? 1 : Integer.parseInt(request.getParameter("edocType"));
    	
    	String defaultListType = Strings.isNotBlank(request.getParameter("list"))?request.getParameter("list"):EdocNavigationEnum.RegisterListState.registerPending.getKey();
        String listType = Strings.isBlank(request.getParameter("listType")) ? defaultListType : request.getParameter("listType");
        //登记状态 0草稿箱 1未登记 2已登记 3退回到签收 4退件箱 5被删除
        int state = EdocNavigationEnum.RegisterListState.getEnumByKey(listType).getValue();
        //登记类型 1自动 2纸质 3二维码  
        int registerType = EdocNavigationEnum.RegisterListType.getEnumByKey(listType).getValue();    
        
        Map<String, Object> condition = new HashMap<String, Object>();
    	condition.put("conditionKey", request.getParameter("condition"));
    	condition.put("textfield", request.getParameter("textfield"));
    	condition.put("textfield1", request.getParameter("textfield1"));
    	condition.put("edocType", edocType);
    	condition.put("userId",  CurrentUser.get().getId());
    	condition.put("registerType", registerType); 
        
        List<EdocRegister> list = new ArrayList<EdocRegister>(); 
        if(state == EdocNavigationEnum.RegisterState.DraftBox.ordinal() || state == EdocNavigationEnum.RegisterState.Registed.ordinal() || state == EdocNavigationEnum.RegisterState.retreat.ordinal()) {
        	list = edocRegisterManager.findEdocRegisterList(state, condition);
        } else {
        	//目前待登记里就显示自动登记
        	if(registerType == EdocNavigationEnum.RegisterType.ByAutomatic.ordinal() || registerType == EdocNavigationEnum.RegisterType.All.ordinal()) {                
        		List<EdocRecieveRecord> recieveList = recieveEdocManager.findWaitEdocRegisterList(state, condition);
                if(recieveList != null) { 
                    EdocRegister edocRegister = null;
                    RegisterBody registerBody = null;
                    EdocSummary summary = null;
                    V3xOrgAccount account = null;
                    V3xOrgDepartment dept = null;
                    for(EdocRecieveRecord r : recieveList){
                        long sendUnitId = r.getExchangeOrgId();
                        if(r.getExchangeType() == 2) {
                            dept = orgManager.getDepartmentById(r.getExchangeOrgId());
                            if(dept!=null) {
                                sendUnitId = dept.getOrgAccountId();
                            }
                        }
                        account = orgManager.getAccountById(sendUnitId);
                        edocRegister = new EdocRegister();
                        edocRegister.setId(-1);
                        edocRegister.setExchangeType(r.getExchangeType());
                        edocRegister.setExchangeOrgId(r.getExchangeOrgId());
                        edocRegister.setSendUnitId(sendUnitId);
                        edocRegister.setIsRetreat(r.getIsRetreat());
                        edocRegister.setSendUnit(account==null?"":account.getName());
                        edocRegister.setEdocType(com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_REC);
                        edocRegister.setEdocUnit(r.getSendUnit());
                        edocRegister.setEdocId(r.getEdocId());
                        edocRegister.setRecieveId(r.getId());                        
                        edocRegister.setSubject(r.getSubject());
                        edocRegister.setDocMark(r.getDocMark());
                        edocRegister.setSecretLevel(r.getSecretLevel());
                        edocRegister.setUrgentLevel(r.getUrgentLevel());
                        edocRegister.setKeepPeriod(r.getKeepPeriod());
                        edocRegister.setCopies(r.getCopies());
                        edocRegister.setRegisterUserName(r.getRegisterName());
                        edocRegister.setRecTime(r.getRecTime()); 
                        summary = edocSummaryManager.findById(r.getEdocId());
                        edocRegister.setSendTo(r.getSendTo());
                        edocRegister.setEdocUnit(summary==null? "":summary.getSendUnit());
                        edocRegister.setKeywords(summary==null? "":summary.getKeywords());
                        edocRegister.setIssuer(summary==null? "" : summary.getIssuer());  
                        edocRegister.setIdentifier(summary==null? "00000000000000000000" : summary.getIdentifier());
                        edocRegister.setState(1);
                        edocRegister.setRegisterUserId(r.getRegisterUserId());
                        edocRegister.setProxy(r.isProxy());
                        edocRegister.setProxyId(r.getProxyUserId()==null?-1:r.getProxyUserId());
                        edocRegister.setProxyLabel(r.getProxyLabel());
                        registerBody = new RegisterBody();
                        registerBody.setContentType(summary==null? "HTML" : summary.getBody(0).getContentType());
                        edocRegister.setRegisterBody(registerBody);
                        list.add(edocRegister);
                    }
                }
            }
        }
        //常用变量
        mav.addObject("state", state);
        mav.addObject("listType", listType);
        mav.addObject("registerType", registerType);
        mav.addObject("edocType", edocType); 
        mav.addObject("controller", "edocController.do");
        //收文登记与分发权限
        boolean canUpdateContent = EdocSwitchHelper.canUpdateAtOutRegist();
        boolean isEdocCreateRegister = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.recEdoc.ordinal());
        boolean isEdocDistribute = EdocRoleHelper.isEdocCreateRole(user.getLoginAccount(), user.getId(), EdocEnum.edocType.distributeEdoc.ordinal());
        mav.addObject("isEdocCreateRegister", isEdocCreateRegister);
        mav.addObject("isEdocDistribute", isEdocDistribute);
        mav.addObject("canUpdateContent", canUpdateContent);
        //枚举类型
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);
        mav.addObject("colMetadata", colMetadata);       
        //加载对象
        //mav.addObject("list", pagenate(list));//lijl注销        
        mav.addObject("list",list);//lijl添加,修改GOV-348.公文登记页面，分发页面不能翻页.        
        
        //发文拟文权限(注意是发文的)
     	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
     	mav.addObject("isEdocCreateRole", isEdocCreateRole);
     	
        return mav;
    }
    //wangjingjing 分发待办事项 begin
    public ModelAndView edocRecDistribute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	return new ModelAndView("edoc/edocFrameEntryPending");
    }
    public ModelAndView edocRecDistributeStep2(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	return new ModelAndView("edoc/edocFramePending");
    }
    //wangjingjing 分发待办事项 end
    
    /** 分发列表 */
    public ModelAndView listDistribute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = CurrentUser.get();      
        Long userId=user.getId();        
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        String[] values = new String[2];
		values[0] = textfield;
		values[1] = textfield1; 
        ModelAndView mav = new ModelAndView("edoc/listDistribute");        
        List<EdocRecieveRecord> list = recieveEdocManager.getWaitRegisterEdocRecieveRecords(userId);
        if(list != null)
            for(EdocRecieveRecord r : list){
                EdocSummary summary = edocSummaryManager.findById(r.getEdocId());
                r.setCopies(summary==null?0:summary.getCopies());
            }
        // lijl获取待分发数据----------------------------------------------------------------Start
		List<EdocSummaryModel> summaryList = new ArrayList<EdocSummaryModel>();
		EdocSummary edocSummary = null;
		EdocSummaryModel edocSummaryModel = null;
		String btnTypeStr = request.getParameter("btnType");
		int btnType = 0;
		if (btnTypeStr != null && !"".equals(btnTypeStr)) {
			btnType = Integer.parseInt(btnTypeStr);
		} else {
			btnType = 2;// 默认是待分发的数据
		}
		List<EdocRegister> 	pendingList = null;

		//时间分类查询（本日，昨日，本周等）
		String listType=request.getParameter("listType"); 
		int listTypeInt=0;
		if(listType!=null && !"".equals(listType)){
			listTypeInt=Integer.parseInt(listType);
			condition="registerDate";
			String[] dateFields=com.seeyon.v3x.edoc.util.DateUtil.getTimeTextFiledByTimeEnum(listTypeInt);
			values[0] = dateFields[0];
			values[1] = dateFields[1];
		}
		pendingList = edocRegisterManager.findRegisterByState(condition,values,btnType,this.getCurrentUser());

		for (EdocRegister edocRegister : pendingList) {
			String serialNo=edocRegister.getSerialNo();
			//lijl处理内部文号0|内部文号||3------------------------------------Start
			if(serialNo!=null&&!"".equals(serialNo)){
				serialNo=serialNo.replace("0|","");
				serialNo=serialNo.replace("||3","");
			}
			edocRegister.setSerialNo(serialNo);
			//lijl处理内部文号0|内部文号||3------------------------------------End
			edocSummary = new EdocSummary();
			edocSummaryModel = new EdocSummaryModel();
			if (edocRegister != null) {
				BeanUtils.copyProperties(edocSummary, edocRegister);
				edocSummary.setId(-1L);//待分时，EdocSummary数据为空，这里赋值为-1，上一个操作把id赋值给了分发对象
				// puyc 修改Id取值错误--这句话还是注释掉了。非常奇怪的代码，居然用edocRegister的id设置edocSummary的id，然后到listDistribute去直接用edocSummary的id，很危险，容易让以后的人误解。
				
//				edocSummary.setId(edocRegister.getEdocId());  //不要轻易修改这个地方，会引起页面的id传递参数错误
			}
			if (btnType == 2) {//2由前台传入, 已分发按钮,需查询发起人
				V3xOrgMember v3xOrgMember = this.orgManager.getMemberById(edocRegister.getDistributerId());
				edocSummary.setStartMember(v3xOrgMember);
				//查询该公文是否已归档
				EdocSummary summary=edocSummaryManager.findById(edocRegister.getEdocId());
				if(summary!=null){
					edocSummary.setHasArchive(summary.getHasArchive());
				}
			} 
			
			//-------------待分发列表没有显示word图标bug 修复  changyi add
			List<Affair> affairs = affairManager.findByObject(ApplicationCategoryEnum.edoc,edocRegister.getId());
			if(affairs != null && affairs.size() > 0){
				edocSummaryModel.setBodyType(affairs.get(0).getBodyType());
			}
			//-------------待分发列表没有显示word图标bug 修复			
			
			//GOV-3338 （需求检查）【公文管理】-【收文管理】，待登记、已登记和待分发列表里'转发文'时选择收文关联新发文，但是打开收文后没有关联发文记录
			//设置公文登记的类型，是纸质的还是电子的
			edocSummaryModel.setRegisterId(edocRegister.getId());
			edocSummaryModel.setRegisterType(edocRegister.getRegisterType());
			edocSummaryModel.setEdocId(edocRegister.getEdocId()); //设置公文id
			
			edocSummaryModel.setSummary(edocSummary);       
			//lijl添加,GOV-3245.A设置B为代理人，他们的待分发下显示出来了以前设置的代理事项.--------------------------------Start
			if(edocRegister.getProxyUserId() != null&&!"".equals(edocRegister.getProxyUserId())){//判断是否有代理
            	List<AgentModel> _agentModelList = MemberAgentBean.getInstance().getAgentModelList(user.getId());//获取被理人
            	if(_agentModelList!=null){
            		if(_agentModelList.size()>0){
            			for(int i=0;i<_agentModelList.size();i++){
            				AgentModel agentModel=_agentModelList.get(i);
            				if(edocRegister.getRegisterUserId()==agentModel.getAgentToId()){//如果登记人的ID等于被代理人的ID则设置代理信息
            					Date start=agentModel.getStartDate();//获取代理的开如时间
            					Date end=agentModel.getEndDate();//获取代理的结整束时间
            					Date now=edocRegister.getRegisterDate();//获取接收的时间
            					if((start.getTime()<=now.getTime()) && (now.getTime()<=end.getTime())){//判断该公文接收的时间是否是在这个代理时间之内
            						edocRegister.setProxyUserId(edocRegister.getProxyUserId());
            						edocSummaryModel.setProxy(edocRegister.isProxy());
            						edocSummaryModel.setProxyName(edocRegister.getProxyUserId()!=null?orgManager.getMemberById(edocRegister.getProxyUserId()).getName():"");
            						summaryList.add(edocSummaryModel);
            					}else{
            						//如果不在不做处理
            					}
            				}else{
            					//如果签收人不等于被代理人也不做处理
            				}
            			}
            		}else{
            			summaryList.add(edocSummaryModel);
            		}
            	}else{
            		summaryList.add(edocSummaryModel);
            	}
            }else{
            	summaryList.add(edocSummaryModel);
            }
			//lijl添加,GOV-3245.A设置B为代理人，他们的待分发下显示出来了以前设置的代理事项.--------------------------------End
			//puyc 代理
			//edocSummaryModel.setProxy(edocRegister.isProxy());
		//	if(edocRegister.getProxyUserId()!=null){
				//V3xOrgMember proxyMember = this.orgManager.getMemberById(edocRegister.getProxyUserId());
			  // edocSummaryModel.setProxyName(proxyMember.getName());
			//}
			
		}
		mav.addObject("pendingList", summaryList);
		// lijl获取待分发数据----------------------------------------------------------------End
        mav.addObject("edocType", EdocEnum.edocType.recEdoc.ordinal()); 
        mav.addObject("controller", "edocController.do");
        mav.addObject("newEdoclabel", "edoc.new.type.rec");
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
        mav.addObject("colMetadata", colMetadata);
        mav.addObject("list", list);
        //发文拟文权限(注意是发文的)
     	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
     	mav.addObject("isEdocCreateRole", isEdocCreateRole);
        return mav;
    }
    
    /**
     * 收文分发列表页的退件箱：退回到登记(已发中退回，退件箱中退回)
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
	@SuppressWarnings("deprecation")
	public ModelAndView distributeRetreat(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.getSession().removeAttribute("transmitSendAtts");  
		
		Long id = Strings.isBlank(request.getParameter("id"))?-1:Long.parseLong(request.getParameter("id"));
		Long registerId = Strings.isBlank(request.getParameter("registerId"))?-1:Long.parseLong(request.getParameter("registerId"));
		String stepBackInfo = request.getParameter("stepBackInfo");//退回备注
		String subject = "";//消息标题
		String distributeName = "";//接受者名字
		long edocId = 0l;//公文id
		long createId = 0l;//接收者id
		long sendId = 0l;//发送者id
		
		EdocRegister edocRegister = null;

		//收文分发退回到登记
		if(id != -1) {
			EdocSummary summary = edocSummaryManager.findById(id);
			if(summary != null) {
				List<EdocRegister> list = edocRegisterManager.findRegister(summary.getId());
				if(list!=null && list.size()>0) {
					edocRegister = list.get(0);
				}
				affairManager.deleteByObject(ApplicationCategoryEnum.edocRec, summary.getId());
				//删除收文(暂逻辑删除)
				edocSummaryManager.updateEdocSummaryState(summary.getId(), Constant.flowState.deleted.ordinal());			
			}
		}
		
		if(registerId != -1) {
			if(edocRegister == null) {
				edocRegister = edocRegisterManager.getEdocRegister(registerId);
			}
		}
		
		if(edocRegister != null) {
			edocRegister.setIsRetreat(RegisterRetreatState.Retreated.ordinal());
			edocRegister.setState(RegisterState.retreat.ordinal());
			edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.WaitDistribute.ordinal());
			edocRegister.setDistributeEdocId(-1);
			edocRegister.setDistributeDate(null);
			subject = edocRegister.getSubject();
			distributeName = edocRegister.getDistributer();
			edocId = edocRegister.getEdocId();
			createId = edocRegister.getCreateUserId();
			sendId = edocRegister.getDistributerId();
			edocRegisterManager.updateEdocRegister(edocRegister);

			//删除分发待办
			Map<String, Object> columns = new Hashtable<String, Object>();
			columns.put("isDelete", true);
			affairManager.update(columns, new Object[][]{
					{"app", ApplicationCategoryEnum.edocRecDistribute.getKey()},
					{"state", StateEnum.edoc_exchange_register.key()}});
			
			//给登记人发送退回消息
			MessageReceiver receiver = new MessageReceiver(edocId,createId);
			userMessageManager.sendSystemMessage(new MessageContent("exchange.stepback", subject,distributeName,stepBackInfo), ApplicationCategoryEnum.edocRegister,sendId,receiver);
			
			//添加登记待办
			User user = CurrentUser.get();
			
			if(edocRegister.getRegisterType()==1) {//电子登记
				if(edocRegister.getEdocId()!=-1 && edocRegister.getRecieveId()!=-1) {
					columns = new Hashtable<String, Object>();
					columns.put("isDelete", true);
					affairManager.update(columns, new Object[][]{
							{"app", ApplicationCategoryEnum.edocRegister.getKey()},
							{"objectId", edocRegister.getEdocId()},
							{"subObjectId", edocRegister.getRecieveId()}});
				}
			} else {//纸质、二维码登记
				columns = new Hashtable<String, Object>();
				columns.put("isDelete", true);
				affairManager.update(columns, new Object[][]{
						{"app", ApplicationCategoryEnum.edocRegister.getKey()},
						{"objectId", edocRegister.getId()}});
			}
			
			//添加收文分发退回到收文登记标识，EdocSummary表就不用做标识了，Affair的isDelete做标识
			Affair affair = new Affair();
			affair.setIdIfNew();
			affair.setApp(ApplicationCategoryEnum.edocRegister.getKey());
			affair.setSubject(edocRegister.getSubject());
			affair.setMemberId(edocRegister.getRegisterUserId());
			affair.setIsFinish(false);
			
			affair.setCreateDate(new Timestamp(System.currentTimeMillis()));
			if(edocRegister.getRegisterType()==1 && edocRegister.getEdocId()!=-1 && edocRegister.getRecieveId()!=-1) {
				affair.setObjectId(edocRegister.getEdocId()); 
			} else {
				affair.setObjectId(edocRegister.getId());
			}
			affair.setSubObjectId(edocRegister.getRecieveId());
			affair.setSenderId(user.getId());
			affair.setState(StateEnum.edoc_exchange_register.key());
			affair.addExtProperty(EdocNavigationEnum.EdocRetreat.edocRegisterRetreat.name(), user.getId());
			affair.serialExtProperties();
			affairManager.addAffair(affair);
			//MessageReceiver receiver_a = new MessageReceiver(affair.getId(), affair.getMemberId(), "message.link.exchange.receive", affair.getSubObjectId().toString());
			//userMessageManager.sendSystemMessage(new MessageContent(key, affair.getSubject(), senderName), ApplicationCategoryEnum.exSign, user.getId(), receiver_a);
		}		
		
		// 回退成功后，跳到待办列表
		//GOV-3546 【公文管理】-【收文管理】-【分发】，待分发收文退回后跳转到退件箱页面去了
//		return super.redirectModelAndView("/edocController.do?method=listWaitSend&edocType=1&list=retreat");
		return super.redirectModelAndView("/edocController.do?method=listDistribute&edocType=1&list=aistributining&btnType=2");
	}
	/**收文待办退回功能:从收文的退件箱退回到待分发列表*/
	public ModelAndView listPendingRetreat(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		request.getSession().removeAttribute("transmitSendAtts");
		User user = CurrentUser.get();
		String _sumaaryId = request.getParameter("resgisterId");
		String _affairId = request.getParameter("checkAffirId");
		String stepBackInfo = request.getParameter("stepBackInfo");//退回备注
		String subject = "";//消息标题
		String distributeName = user.getName();//发送者名字
		long edocId = 0l;//公文id
		long distributeNameId = 0l;//接收者id
		long sendId = user.getId();//发送者id
		//删除个人流程。
        long affairId = Long.parseLong(_affairId);
		edocManager.deleteAffair("draft",affairId);
		//更改待分发状态。
		long summaryId = Long.parseLong(_sumaaryId);
		List<EdocRegister> reg = edocRegisterManager.findRegister(summaryId);
		//收文待办退回到分发的待分发
		EdocRegister register = null;
		if(reg.size()>0){
			register = reg.get(0);
		}
		long id = register.getId();
		EdocRegister edocRegister = edocRegisterManager.getEdocRegister(id);
		//设置待分发为2
		edocRegister.setState(EdocNavigationEnum.RegisterState.Registed.ordinal());
		edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.WaitDistribute.ordinal());//distribute_state是分发状态。
		//设置为被退回状态
		edocRegister.setIsRetreat(1);
		subject = edocRegister.getSubject();
		edocId = edocRegister.getEdocId();
		distributeNameId = edocRegister.getDistributerId();
		edocRegisterManager.updateEdocRegister(edocRegister);	
		
		//给登记人发送退回消息
		MessageReceiver receiver = new MessageReceiver(edocId,distributeNameId);
		userMessageManager.sendSystemMessage(new MessageContent(
				"exchange.stepback", subject,distributeName,stepBackInfo),
				ApplicationCategoryEnum.edocRegister,sendId,receiver);
		// 回退成功后，跳到待办列表?
		return super.refreshWorkspace();
	}
    
    /** 待阅列表 */
    public ModelAndView listReading(HttpServletRequest request, HttpServletResponse response) throws Exception {request.getSession().removeAttribute("transmitSendAtts");  
	 ModelAndView modelAndView = new ModelAndView("edoc/listReading");
 	/*    	 
 	List <V3xOrgMember> mems=EdocRoleHelper.getAccountExchangeUsers();
 	System.out.println(mems.size());
 	List <V3xOrgMember> memsd=EdocRoleHelper.getDepartMentExchangeUsers();
 	System.out.println(memsd.size());
 	boolean isEdocAdmin=EdocRoleHelper.isAccountExchange();
 	isEdocAdmin=EdocRoleHelper.isDepartmentExchange();    	
 	String ids=EdocRoleHelper.getUserExchangeDepartmentIds();
 	System.out.println("department ids="+ids);
 	*/
	 //用于已阅列表中阅转办跳转页面的表示          wangjingjing 开始
	 String pageview = request.getParameter("pageview");
	 if(null == pageview){
		 pageview = "listReading";
	 }
	 modelAndView.addObject("pageview",pageview);
	 //用于已阅列表中阅转办跳转页面的表示          wangjingjing 结束
     String condition = request.getParameter("condition");
     String textfield = request.getParameter("textfield");
     String textfield1 = request.getParameter("textfield1");
     
     String edocType=request.getParameter("edocType");
 	int iEdocType=-1;
 	if(edocType!=null && !"".equals(edocType))
 	{
 		iEdocType=Integer.parseInt(edocType);
 	}
    
 	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("track", track);
    params.put("processType", 2);
     User user = CurrentUser.get();
     V3xOrgMember theMember = null;
     theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());
     
     /***************测试代码开始*****************/
     //Long metadataId=7971699406983548687L;
     //edocManager.useMetadataValue(user.getLoginAccount(),metadataId,"22");
     /***************测试代码结束*****************/
     
     List<EdocSummaryModel> queryList = null;  
     if (theMember.getAgentId() == -1){
         /**********组合查询组件调用开始*****************/
     	String comb_condition = request.getParameter("comb_condition");  //组合查询标识
         if(comb_condition!=null && "1".equals(comb_condition) ){
     		EdocSearchModel em=new EdocSearchModel();
     		bind(request, em);
     		queryList = edocManager.combQueryByCondition(iEdocType,em, StateEnum.col_pending.key(),-1,-1,2);
     		modelAndView.addObject("combQueryObj", em);  //设置的查询条件还原到页面
     		modelAndView.addObject("combCondition", "1");
         }else
         /***************组合查询组件调用结束************/
     	if(condition != null) {
     		if(condition.equals("cusReceiveTime")){ //如果条件来自自定义分类的时间段，设置查询条件和查询起始时间
     			condition="receiveTime";
     			String[] textfield_condition= edocManager.getTimeTextFiledByTimeEnum(Integer.parseInt(textfield));
     			textfield=textfield_condition[0];
     			textfield1=textfield_condition[1];
     			   
     		}
     		
     		queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_pending.key(), params, -1,-1,2);
     	}
     	if (queryList != null) {
     		modelAndView.addObject("pendingList", queryList);
     	} else {
     		List<EdocSummaryModel> pendingList = edocManager.queryTodoList(iEdocType, params);
     		modelAndView.addObject("pendingList", pendingList);
     	}
     }
     else
     {
     	queryList = new ArrayList<EdocSummaryModel>();
     	modelAndView.addObject("pendingList", queryList);
     }

     Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
     Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
     colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
     Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
     colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);           
     //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
     
     //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
     
     /*
      * 元数据中加载 秘密程度
      * cy add
      */
     Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
     colMetadata.put(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);
     
     /*
      * 元数据中加载 紧急程度
      * cy add
      */
     Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
     colMetadata.put(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
     
     
     modelAndView.addObject("colMetadata", colMetadata);
     modelAndView.addObject("controller", "edocController.do");
     modelAndView.addObject("edocType", edocType);
 	
     //是否包含“待登记”按钮
 	boolean hasRegistButton=false;
 	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
 	{
 		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
 		hasRegistButton=true;
 	}
 	else
 	{
 		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
 	}
 	modelAndView.addObject("hasRegistButton", hasRegistButton);
 	
 	//分发权限：阅转办
 	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.distributeEdoc.ordinal());
 	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
 	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
 	modelAndView.addObject("isExchangeRole", isExchangeRole);
	//发文拟文权限:转发文
	boolean isSendEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
	modelAndView.addObject("isSendEdocCreateRole", isSendEdocCreateRole);
	
    return modelAndView;
  }  
    
    
    
    
    
    
    /** 已阅列表 */
    public ModelAndView listReaded(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	request.getSession().removeAttribute("transmitSendAtts"); 
    	ModelAndView modelAndView = new ModelAndView("edoc/listReaded");
    	//用于待阅列表中阅转办跳转页面的表示          wangjingjing 开始
   	 	String pageview = request.getParameter("pageview");
   	 	if(null == pageview){
   	 		pageview = "listReaded";
   	 	}
   	 	modelAndView.addObject("pageview",pageview);
   	 	//用于待阅列表中阅转办跳转页面的表示          wangjingjing 结束
    	/*    	 
    	List <V3xOrgMember> mems=EdocRoleHelper.getAccountExchangeUsers();
    	System.out.println(mems.size());
    	
    	List <V3xOrgMember> memsd=EdocRoleHelper.getDepartMentExchangeUsers();
    	System.out.println(memsd.size());
    	
    	boolean isEdocAdmin=EdocRoleHelper.isAccountExchange();
    	isEdocAdmin=EdocRoleHelper.isDepartmentExchange();    	
    	String ids=EdocRoleHelper.getUserExchangeDepartmentIds();
    	System.out.println("department ids="+ids);
    	*/
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        
        String edocType=request.getParameter("edocType");
    	int iEdocType=-1;
    	if(edocType!=null && !"".equals(edocType))
    	{
    		iEdocType=Integer.parseInt(edocType);
    	}
    	
    	int hasArchive = -1;
    	//lijl添加空值判断
    	String hasArchiveStr=request.getParameter("hasArchive");
    	if(hasArchiveStr!=null&&!"".equals(hasArchiveStr)){
    		if(Strings.isNotBlank(hasArchiveStr)) {
    			try{
    				hasArchive = Integer.parseInt(hasArchiveStr);
    			}catch(Exception ex){
    				hasArchive = -1;
    			}
    		}
    	}
    	int track = Strings.isBlank(request.getParameter("track"))?-1:Integer.parseInt(request.getParameter("track"));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("track", track);
        params.put("processType", 2);
        User user = CurrentUser.get();
        V3xOrgMember theMember = null;
        theMember = orgManager.getEntityById(V3xOrgMember.class,user.getId());
        
        /***************测试代码开始*****************/
        //Long metadataId=7971699406983548687L;
        //edocManager.useMetadataValue(user.getLoginAccount(),metadataId,"22");
        /***************测试代码结束*****************/
        
        List<EdocSummaryModel> queryList = null; 
        if (theMember.getAgentId() == -1){
            /**********组合查询组件调用开始*****************/
         	String comb_condition = request.getParameter("comb_condition");  //组合查询标识
             if(comb_condition!=null && "1".equals(comb_condition) ){
         		EdocSearchModel em=new EdocSearchModel();
         		bind(request, em);
         		queryList = edocManager.combQueryByCondition(iEdocType,em, StateEnum.col_done.key(),-1,hasArchive,2);
         		modelAndView.addObject("combQueryObj", em);  //设置的查询条件还原到页面
         		modelAndView.addObject("combCondition", "1");
             }else
             /***************组合查询组件调用结束************/
        	if(condition != null) {
        		if(condition.equals("cusReceiveTime")){ //如果条件来自自定义分类的时间段，设置查询条件和查询起始时间
        			condition="receiveTime";
        			String[] textfield_condition= edocManager.getTimeTextFiledByTimeEnum(Integer.parseInt(textfield));
        			textfield=textfield_condition[0];
        			textfield1=textfield_condition[1];
        			
        		}
        		
        		queryList = edocManager.queryByCondition(iEdocType,condition, textfield, textfield1,  StateEnum.col_done.key(), params, -1,hasArchive,2);
        	}
        	//wangjingjing 当不是组合查询，也不是自定义查询时执行 begin
            /*
        	if (queryList != null) {
        		modelAndView.addObject("pendingList", queryList);
        	} else {
        		List<EdocSummaryModel> pendingList = edocManager.queryTodoList(iEdocType);
        		modelAndView.addObject("pendingList", pendingList);
        	}
        	*/
        	else{
        		queryList = edocManager.queryByCondition(iEdocType,"", null, null,  StateEnum.col_done.key(), params, -1,hasArchive,2);
        	}
            //wangjingjing end
        }
        //wangjingjing begin
        /*
        else
        {
        	queryList = new ArrayList<EdocSummaryModel>();
        	modelAndView.addObject("pendingList", queryList);
        }
        */
        modelAndView.addObject("pendingList", queryList);
        //wangjingjing end

        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);           
        //Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        //modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        
        /*
         * 元数据中加载 秘密程度
         * cy add
         */
        Metadata secretLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        colMetadata.put(MetadataNameEnum.edoc_secret_level.toString(), secretLevel);
        
        /*
         * 元数据中加载 紧急程度
         * cy add
         */
        Metadata urgentLevel = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        colMetadata.put(MetadataNameEnum.edoc_urgent_level.toString(), urgentLevel);
        
        
        modelAndView.addObject("colMetadata", colMetadata);
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("edocType", edocType);
    	
        //是否包含“待登记”按钮
    	boolean hasRegistButton=false;
    	if(EdocEnum.edocType.recEdoc.ordinal()==iEdocType)
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.rec");
    		hasRegistButton=true;
    	}
    	else
    	{
    		modelAndView.addObject("newEdoclabel", "edoc.new.type.send");
    	}
    	modelAndView.addObject("hasRegistButton", hasRegistButton);
    	//收文分发权限判断，应传入收文分发参数
    	boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.distributeEdoc.ordinal());
    	boolean isExchangeRole=EdocRoleHelper.isExchangeRole();
    	modelAndView.addObject("isEdocCreateRole", isEdocCreateRole);
    	modelAndView.addObject("isExchangeRole", isExchangeRole);
    	
    	//发文拟文权限
    	boolean isSendEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
    	modelAndView.addObject("isSendEdocCreateRole", isSendEdocCreateRole);
    	
        return modelAndView;
    }       
    
    
    /**
     * 正常处理公文
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView finishWorkItem(HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
    	String allNodes = request.getParameter("allNodes"); 
    	String branchNodes = request.getParameter("branchNodes");
    	//json格式的字符串:选人
    	String popNodeSelected = request.getParameter("popNodeSelected");
    	//json格式的字符串:条件分支
    	String popNodeCondition = request.getParameter("popNodeCondition");
    	//json格式的字符串:新流程信息
    	String popNodeNewFlow = request.getParameter("popNodeNewFlow");
    	if(log.isInfoEnabled()){
    		log.info("popNodeSelected:="+popNodeSelected);
        	log.info("popNodeCondition:="+popNodeCondition);
        	log.info("popNodeNewFlow:="+popNodeNewFlow);
    	}
    	boolean lostBranchData = branchNodes != null && !branchNodes.equals(allNodes);
    	if(Strings.isBlank(request.getParameter("__ActionToken")) || lostBranchData){
    		if(lostBranchData)
    			log.error("不能获取分支数据，affairId:"+request.getParameter("affairId")+" summaryId:"+request.getParameter("summary_id")+" allNodes:"+allNodes+" branchNodes:"+branchNodes);
    		PrintWriter out = response.getWriter();
    		out.println("<script>alert('操作失败：网络异常，系统无法获取所需的提交数据。');");
    		out.println("try {parent.getA8Top().endProc();}");
    		out.println("catch (e) {};");
    		out.println("parent.doEndSign_pending();");
    		out.println("</script>");
    		return null;
    	}
    	
		// 选择的特定的单位公文收发员
		String edocMangerID = request.getParameter("memberList");

    	User user = CurrentUser.get();
        String sSummaryId = request.getParameter("summary_id"); 
        long summaryId = Long.parseLong(sSummaryId);
        
        String processId = request.getParameter("processId");
        boolean isRelieveLock = true;
        EdocSummary summary = null;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.finishWorkItem,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        
	        String _affairId = request.getParameter("affairId");
	        Long affairId = null;
	        try {
	            affairId = new Long(_affairId);
	        } catch (Exception ex) {
	
	        }
	        
	        Affair affair = affairManager.getById(affairId);
	        if(affair == null || affair.getState() != StateEnum.col_pending.key())
	        {
	        	response.getWriter().println("<script>alert(\""+EdocHelper.getErrorMsgByAffair(affair)+"\");parent.doEndSign_pending();</script>");
	        	return null;
	        }
	
	        EdocOpinion signOpinion = new EdocOpinion();
	        bind(request, signOpinion);
	      //lijl添加,在填写意见的时候,同一个用户,同一个节点域不同的节点,只保留最后的意见----------Start
	        if(!flag){//如果为true则说明,是保留所有意见,则不需要修改state状态,如果是false则表示只显示最后一条意见,因此要设置state状态为1
	        	flag=false;
	        	String optionType=request.getParameter("optionType");
	        	String summaryIdStr=request.getParameter("summary_id");
	        	//String policy1=request.getParameter("policy");
	        	Long summary_id=0L;
	        	if(summaryIdStr!=null&&!"".equals(summaryIdStr)){
	        		summary_id=Long.parseLong(summaryIdStr);
	        	}
	        	//如果选择的是"退回时办理人选择覆盖方式,其他保留最后意见",将在同一个节点权限域,的其他意见全部设置为1
	        	if("3".equals(optionType)){
	        		edocManager.update(summary_id, user.getId(),signOpinion.getPolicy(),1,0);
	        	}
	        	//lijl添加,在填写意见的时候,同一个用户,同一个节点域不同的节点,只保留最后的意见----------End
	        }
	        signOpinion.setCreateUserId(affair.getMemberId());
	        
	        String attitude = request.getParameter("attitude");
	        if(!Strings.isBlank(attitude)){
	        	signOpinion.setAttribute(Integer.valueOf(attitude).intValue());
	        }else{
	        	signOpinion.setAttribute(com.seeyon.v3x.edoc.util.Constants.EDOC_ATTITUDE_NULL);
	        }
	        String content = request.getParameter("contentOP");
	        signOpinion.setContent(content);
	        String[] afterSign = request.getParameterValues("afterSign");
	        Set<String> opts = new HashSet<String>();
	        if(afterSign!=null){
		        for(String option : afterSign){
		        	opts.add(option);
		        }
	        }
	        //允许处理后归档和跟踪被同时选中，但是他们都不能和删除按钮同时选中
	        if(opts.size()>1 && opts.contains("delete")){
	        	opts.remove("delete");
	        }
	        signOpinion.isDeleteImmediate = opts.contains("delete");
	        boolean track =  opts.contains("track");
	        signOpinion.affairIsTrack = track;
	        signOpinion.isPipeonhole = opts.contains("pipeonhole");
	
	        
	        String trackMembers = request.getParameter("trackMembers");
	        String trackRange = request.getParameter("trackRange");
	        //不跟踪 或者 全部跟踪的时候不向部门跟踪表中添加数据，所以将下面这个参数串设置为空。
	        if(!track || "1".equals(trackRange)) trackMembers = "";
	        setTrack(affairId, track, trackMembers);
	        
	        signOpinion.setIsHidden(request.getParameterValues("isHidden") != null);
	        signOpinion.setIdIfNew();
	                
	        long nodeId=-1;
	        if(request.getParameter("currentNodeId")!=null && !"".equals(request.getParameter("currentNodeId")))
	        {
	        	nodeId=Long.parseLong(request.getParameter("currentNodeId"));
	        }
	        /*Manager可以得到，不需要再这里设置。
	         * signOpinion.setNodeId(nodeId);
	        //设置代理人信息
	        if(user.getId()!= affair.getMemberId())
	        {
	        	signOpinion.setProxyName(user.getName());
	        }
	         */
	        String manualSelect = request.getParameter("manual_select");
	        if(manualSelect==null || manualSelect.equals("")){
	            manualSelect = null;
	        }
	        Map<String, String[]> map = PopSelectParseUtil.getPopNodeSelectedValues(popNodeSelected);
//	        String[] manualSelectNodeId = request.getParameterValues("manual_select_node_id");
//	        Map<String, String[]> map = new HashMap<String, String[]>();
//	        if(manualSelectNodeId != null){
//	            for(String node : manualSelectNodeId){
//	                String[] people = request.getParameterValues("manual_select_node_id" + node);
//	
//	                map.put(node, people);
//	            }
//	        }
//	     	// 分支流程
	        //key - 节点Id  value - 是否选择 true|false
//	        Map<String,String> condition = new HashMap<String,String>();
//	        if(allNodes != null){
//	        	String[] nodes = StringUtils.split(allNodes,":");
//	        	String result = "";
//	        	if(nodes != null){
//	        		for(String node:nodes){
//	        			result = request.getParameter("condition"+node);
//	        			result = "on".equals(result)?"false":"true";    //传递给后台的isDelete属性，所以要取反
//	        			condition.put(node, result);
//	        			if("true".equals(result))
//	        				map.remove(node);
//	        		}
//	        	}
//	        }
	        Map<String,String> condition = PopSelectParseUtil.getPopNodeConditionValues(popNodeCondition, map);
	        
	        if(condition.size()>0){
	        	if(!EdocHelper.hasNodeExist(affair, condition)){
	        		response.getWriter().println("<script>alert(\""+com.seeyon.v3x.edoc.util.Constants.getString("workflow.branchNotSyn")+"\");parent.doEndSign_pending();</script>");
		        	return null;
	        	}
	        }
	        
	        String exchangeType=request.getParameter("edocExchangeType");
	        if(exchangeType!=null && !"".endsWith(exchangeType))
	        {
	        	signOpinion.exchangeType=Integer.parseInt(exchangeType);        	
	        }
	        
	        //-- 督办,如果下列三项参数有一项为空, 即调用原始的finishWorkItem方法 : 否则调用重载后加督办的finishWorkItem方法
	        String spMemberId = request.getParameter("supervisorId");
	        String superviseDate = request.getParameter("awakeDate");
	        String supervisorNames = request.getParameter("supervisors");
	        String title = request.getParameter("superviseTitle");
	        
	        //太原市政府二开  上卡功能  郝后成  2012-07-25
	        String formId = request.getParameter("formId");
	        
	        summary = edocManager.getEdocSummaryById(summaryId, true); 
	        //太原市政府二开  上卡功能  郝后成  2012-07-25
	        if(Strings.isNotBlank(formId)){
	        	summary.setFormId(Long.parseLong(formId));
	        }
	        
	        String docMark = request.getParameter("docMark"); 
	        String serialNo = request.getParameter("serialNo"); 
	        
	        //-8222600899131324823|蓉内[2012]第0417号|417|1  (文号是这种形式了，需要处理)
	        if(Strings.isNotBlank(docMark)){
	        	String[] docMarks = docMark.split("\\|");
	        	if(docMarks.length > 1)
	        	summary.setDocMark(docMarks[1]);
	        }
	        if(Strings.isNotBlank(serialNo)){
	        	String[] serialNos = serialNo.split("\\|");
	        	if(serialNos.length > 1)
	        	summary.setSerialNo(serialNos[1]);
	        }
	        
	        //设置手动选择的归档路径ID
	        String archiveId=request.getParameter("archiveId");
	        if(Strings.isNotBlank(archiveId) && signOpinion.isPipeonhole){
	        	summary.setArchiveId(Long.parseLong(archiveId));
	        }
	        //为了保存流程日志中修改附件的记录在处理提交之前，所以将保存附件的操作提前了。bug29527
	        //保存附件
	        String oldOpinionIdStr=request.getParameter("oldOpinionId"); 
	        if(!"".equals(oldOpinionIdStr))
	        {//删除原来意见,上传附件等
	        	Long oldOpinionId=Long.parseLong(oldOpinionIdStr);
	        	attachmentManager.deleteByReference(summaryId, oldOpinionId);
	        	edocManager.deleteEdocOpinion(oldOpinionId);
	        }
	        //保存正文的附件,是否修改了正文附件
	        //start 使用附件组件来重构 dongyj
            AttachmentEditHelper editHelper = new AttachmentEditHelper(request);
            if(editHelper.hasEditAtt()){//是否修改附件
            	edocManager.saveUpdateAttInfo(editHelper.attSize(),summaryId,editHelper.parseProcessLog(Long.parseLong(processId), nodeId));
            	appLogManager.insertLog(user, AppLogAction.Edoc_File_update, user.getName(),affair.getSubject());
            } 
        	this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, signOpinion.getId(), request);
            /*
            this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, signOpinion.getId(), request);
            String isContentAttchmentChanged=request.getParameter("isContentAttchmentChanged");
			if("1".equals(isContentAttchmentChanged)){
	        	this.edocManager.updateAttachment(summary,affair,user,request);
        	}*/
	        //end
        	
        	//如果当前操作执行了转PDF的操作。
        	String isConvertPdf=request.getParameter("isConvertPdf");
        	if(Strings.isNotBlank(isConvertPdf)){
        		createPdfBodies(request, summary);
        	}
        	//推送消息    affairId,memberId#affairId,memberId#affairId,memberId
		    String pushMessageMembers = request.getParameter("pushMessageMemberIds");
		    setPushMessagePara2ThreadLocal(pushMessageMembers); 
		    
	        String ret = null;
	        if(null!=supervisorNames && !"".equals(supervisorNames) && null!=spMemberId && !"".equals(spMemberId) && null!=superviseDate && !"".equals(superviseDate)){
	        	ret = edocManager.finishWorkItem(summary, affairId, signOpinion, map,condition, title, spMemberId, supervisorNames,superviseDate, processId, user.getId()+"", edocMangerID);
	        } else {
				ret = edocManager.finishWorkItem(summary, affairId,signOpinion, map, condition, processId, user.getId()+ "", edocMangerID);
				if ("true".equals(request.getParameter("isDeleteSupervisior"))) {
					this.edocSuperviseManager.deleteSuperviseDetailAndSupervisors(summary);
				}
	        }       
	        
	        updateIndexManager.update(summaryId,EdocUtil.getAppCategoryByEdocType(summary.getEdocType()).getKey());
	        //lijl添加,通过流程ID获取刚插入的流程日志对象,并将意见设置到param5中------------------Start
//        	Long processid=0L;
//        	if(summary!=null){
//        		processid=Long.parseLong(summary.getProcessId());
//        	}
//        	ProcessLog processLog=processLogManager.getProcessLogByProcessIdMaxTime(processid);
//        	if(processLog != null) {
//	        	//将意见添加到param5中
//	        	processLog.setParam5(signOpinion.getContent());
//	        	processLogManager.update(processLog);
//        	}
        	//lijl添加,通过流程ID获取刚插入的流程日志对象,并将意见设置到param5中------------------End
	        PrintWriter out = response.getWriter();
	        out.println("<script>");
//	        if("pigeonhole".equals(ret))
//	        {
//	        	out.println("parent.alertPigeonhole();");
//	        }
	        out.println("parent.doEndSign_pending();");
	        out.println("</script>");
	        
	        //--
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
            //解锁正文文单
        	try{
        		unLock(user.getId(),summary);
        	}catch(Exception e){
        		log.error(e);
        	}

        }
        return null;
    }

    /**
     * 联合发文暂时不支持转化为PDF正文
     * @param request
     * @param summary
     */
	private void createPdfBodies(
			HttpServletRequest request, EdocSummary summary) {
		//WORD转PDF正文
		//1、判断当前公文开关是否允许转PDF操作
		//2、获取前台参数
		//3、组装PDF BODY对象
		//4、设置进EDOCSUMMARY中，传至MANAGER层进行处理
		//boolean canConvert=EdocSwitchHelper.canEnablePdfDocChange();
		String isConvertPdf=request.getParameter("isConvertPdf");
		if(Strings.isNotBlank(isConvertPdf)){
			String pdfId=request.getParameter("newPdfIdFirst");
//			String pdfIdSecond=request.getParameter("pdfIdSecond");
			EdocBody  pdfBody=new EdocBody();
//		    EdocBody  pdfBodySend=new EdocBody();
//		    if(summary.getIsunit() && summary.getEdocBodies().size()>1){
//		    	if(summary.getBody(EdocBody.EDOC_BODY_PDF_TWO)==null){//当前公文不存在PDF正文
//		        	pdfBodySend.setIdIfNew();
//		        	pdfBodySend.setContentType(com.seeyon.v3x.common.constants.Constants.EDITOR_TYPE_PDF);
//		        	pdfBodySend.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
//		        	pdfBodySend.setLastUpdate(new java.sql.Timestamp(System.currentTimeMillis()));
//		        	pdfBodySend.setContentNo(EdocBody.EDOC_BODY_PDF_TWO);
//		    	}
//		    	else{//覆盖当前PDF正文。取最新的PDF正文
//		    		pdfBodySend=summary.getBody(EdocBody.EDOC_BODY_PDF_TWO);
//		    		pdfBodySend.setLastUpdate(new java.sql.Timestamp(System.currentTimeMillis()));
//		    	}
//		    	pdfBodySend.setEdocSummary(summary);
//		    	pdfBodySend.setContent(pdfIdSecond);
//		    	summary.getEdocBodies().add(pdfBodySend);
//		    }
		   if(summary.getBody(EdocBody.EDOC_BODY_PDF_ONE)==null){//当前公文不存在PDF正文
		        pdfBody.setIdIfNew();    
		        pdfBody.setContentType(com.seeyon.v3x.common.constants.Constants.EDITOR_TYPE_PDF);
		        pdfBody.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
		        pdfBody.setLastUpdate(new java.sql.Timestamp(System.currentTimeMillis()));
		        pdfBody.setContentNo(EdocBody.EDOC_BODY_PDF_ONE); 
		   }else{//覆盖当前PDF正文。取最新的PDF正文
			   pdfBody=summary.getBody(EdocBody.EDOC_BODY_PDF_ONE);
			   pdfBody.setLastUpdate(new java.sql.Timestamp(System.currentTimeMillis()));
			}
		   	pdfBody.setContent(pdfId);
		   	pdfBody.setEdocSummary(summary);
		    summary.getEdocBodies().add(pdfBody);
		}
	}
	
	
    /**
     * @param request
     * @param response 
     * @return
     * @throws Exception
     */
    public ModelAndView detail(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {      
    	ModelAndView modelAndView = new ModelAndView("edoc/edocDetail"); 
        try { 
        	User user=CurrentUser.get();   
        	Long summaryId = null;
        	boolean showType = false;//关联收文、是否有权限显示公文
			String sendSummaryId = request.getParameter("sendSummaryId"); //从发文关联收文点击进来的,这个是发文summaryId
			String canNotOpen = request.getParameter("canNotOpen");
			if(Strings.isNotBlank(sendSummaryId)){//从关联文点击进来的
				//发文关联收文，在发文流程上的人有权限看收文
				List<Affair> affairs = affairManager.queryALLAvailabilityAffairList(Long.parseLong(sendSummaryId));
				for(int i=0;i<affairs.size();i++){
        			if(user.getId() == affairs.get(i).getMemberId()){
        				showType = true;
        			}
        		}
			}
        	if(!Strings.isBlank(request.getParameter("summaryId"))){
        		summaryId = Long.parseLong(request.getParameter("summaryId"));
        	}
        	Affair affair = null;
        	String _affairId = request.getParameter("affairId");
        	if(Strings.isNotBlank(_affairId)){
        		affair = affairManager.getById(Long.parseLong(_affairId));
        	}
        	else{
        		//取我的Affair，用于访问控制权限校验
        		List<Affair> myAffairs = affairManager.getAffairBySummaryId(ApplicationCategoryEnum.edoc, summaryId, user.getId());
        		if(myAffairs!=null && !myAffairs.isEmpty()){
        			affair = myAffairs.get(0);
        		}
        		else{
        			affair = affairManager.getCollaborationSenderAffair(summaryId);
        		}
        	}   
        	if(affair == null || affair.getIsDelete() ||     
            		(affair.getState() != StateEnum.col_pending.key() 
                    		&& affair.getState() != StateEnum.col_sent.key()
                    		&& affair.getState() != StateEnum.col_waitSend.key()
                    		&& affair.getState() != StateEnum.col_done.key())){
        		
                String msg=ColHelper.getErrorMsgByAffair(affair); 
                //修复bug
                //GOV-491 a拟文，b/c审核，b不同意，提交给c，c退回，b退回给发起人，a查看，提示的是被撤销，应该是被退回   ---start
                //这里有加入了 affair非空的判断，不然这里会产生空指针
                if(affair != null && affair.getState() == StateEnum.col_cancel.key()){  // 

                	if(Strings.isBlank(_affairId)){
                	
	                	summaryId = affair.getObjectId();
	                	
	                	//获得发起人的affair 
	                	affair = affairManager.getWaitSendBysummaryIdAndState(ApplicationCategoryEnum.edocSend, summaryId,1);
	          
	                	if(affair.getSubState() == SubStateEnum.col_waitSend_stepBack.ordinal()){ 
	                		String state = Constant.getString4CurrentUser("col.state.6.stepback");
	                		String appName=Constant.getCommonString("application."+affair.getApp()+".label");
	            	    	msg = Constant.getString4CurrentUser("col.state.invalidation.alert", affair.getSubject(), state,appName, 0, null);
	                	}
                	}
                }
                //GOV-491 a拟文，b/c审核，b不同意，提交给c，c退回，b退回给发起人，a查看，提示的是被撤销，应该是被退回   ---end
                throw new ColException(msg);
            }
        	if(Strings.isNotBlank(_affairId)){
	        	//标记为已读状态。
	        	try{
	        		ColHelper.updateAffairStateWhenClick(affair, affairManager);
	        	}catch(Exception e){log.error(e);return null;}
        	}
        	if(summaryId == null){
        		summaryId=affair.getObjectId();
        	}
        	
        	long relationSummaryId = summaryId;
        	
        	String detailType = request.getParameter("detailType"); 
        	modelAndView.addObject("forwardType",detailType);
        	//如果是从已分发列表中查看详细信息
        	String edocType=request.getParameter("edocType");
        	List<EdocSummary> newEdocList = null;
        	if("1".equals(edocType) && "listSent".equals(detailType)){ 
        		String edocId = request.getParameter("edocId");
        		relationSummaryId = Long.parseLong(edocId);
        		
        		List<EdocSummary> allEdocList = new ArrayList<EdocSummary>();
        		
        		EdocRegister edocRegister = edocRegisterManager.findRegisterByDistributeEdocId(relationSummaryId);
        		if(edocRegister != null){
        			List<EdocSummary> newEdocList1 = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(
							edocRegister.getId(), user.getId(),
							1,2); 
        			if(newEdocList1 != null){
        				allEdocList.addAll(newEdocList1);
    				}
				}
				
				List<EdocSummary> newEdocList2 = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(
						relationSummaryId, user.getId(),
						1,2); 
				if(newEdocList2 != null){
					allEdocList.addAll(newEdocList2);
				}
        		
				newEdocList = allEdocList;
        	}
        	
        	
        	/*********puyc 关联发文 * 收文的Id,收文的Type*********/
            String relSends = "haveNot";  
            String relRecs = "haveNot";  
//            List<EdocSummary> newEdocList = this.edocSummaryRelationManager.findNewEdoc(relationSummaryId, user.getId(), 1);
            
            if(detailType == null){
            	newEdocList = this.edocSummaryRelationManager.findNewEdoc(relationSummaryId, user.getId(), 1);
            }
            else if(!"listSent".equals(detailType)){ 
            	newEdocList = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(relationSummaryId, user.getId(), 1,2);
            }
            
            if(newEdocList != null){
            	 relSends = "haveMany";
            	 if("isYes".equals(canNotOpen) || Strings.isNotBlank(sendSummaryId)){
            		 relSends = "haveNot";
             	}
            	 modelAndView.addObject("recEdocId",relationSummaryId);
                 modelAndView.addObject("recType",1);
                 modelAndView.addObject("relSends",relSends);
            } 
            /*********puyc 关联收文  发文的Id 发文的Type**********/
            EdocSummaryRelation edocSummaryRelationR = this.edocSummaryRelationManager.findRecEdoc(summaryId, 0);
            if(edocSummaryRelationR != null){
            	relRecs = "haveMany";
            	if("isYes".equals(canNotOpen) || Strings.isNotBlank(sendSummaryId)){
            		relRecs = "haveNot";
            	}
                modelAndView.addObject("relRecs",relRecs);
            }
            /*********puyc end**********/
        	//SECURITY 访问安全检查
            if(!showType){
        	   if(!SecurityCheck.isLicit(request, response, ApplicationCategoryEnum.edoc, user, summaryId, affair, null)){
        		   return null;
        	   }
            }
        	String list = request.getParameter("list");
        	if(!Strings.isNotBlank(list)){
        		list="popup";
        	}
        	//有可能公文已经处理完了，但是消息提示框仍然在哪里，所以需要重新查询一下当前事项的状态。
        	String from = request.getParameter("from");
        	if(affair.getState().equals(StateEnum.col_done.getKey()) && "Pending".equals(from)) from = "Done";
        	    modelAndView.addObject("sendSummaryId", sendSummaryId);
        	    modelAndView.addObject("summaryId", summaryId);
				modelAndView.addObject("bodyType", affair.getBodyType());
				modelAndView.addObject("openFrom", request.getParameter("openFrom"));
				modelAndView.addObject("controller", "edocController.do");
				modelAndView.addObject("list", list).addObject("from", from);
				//modelAndView.addObject("securityChecks", securityChecks);
				return modelAndView;	
        }
        catch (Exception e) {
        	PrintWriter out = response.getWriter();        	
        	//super.printV3XJS(out);        	
        	out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(e.getMessage()) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"true\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("");
        	out.println("</script>");
        	
        	return null;
		}
    }
    
    
    public ModelAndView edocDetailInDoc(HttpServletRequest request,HttpServletResponse response) throws Exception 
    {
    	String summaryId=request.getParameter("summaryId");
    	Affair affair  = null;
    	if(Strings.isNotBlank(summaryId)){
    		affair = affairManager.getCollaborationSenderAffair(Long.valueOf(summaryId));
    	}
    	ModelAndView mav = new ModelAndView("edoc/edocDetail");
    	mav.addObject("openFrom",request.getParameter("openFrom"));
     	mav.addObject("lenPotent",request.getParameter("lenPotent"));
     	mav.addObject("docId",request.getParameter("docId"));
     	mav.addObject("summaryId",summaryId);
     	mav.addObject("isLibOwner",request.getParameter("isLibOwner"))    	;
     	mav.addObject("controller", "edocController.do");
     	if(affair!=null){
     		mav.addObject("affairId", affair.getId());
     	}
    	return mav;
    }
   

//   /**
//    * 判断归档文件夹是否存在
//    * @param archiveId ：文件夹ID
//    * @return
//    */
//   public  boolean isFolderExsit(Long archiveId){
//	   if(archiveId == null ) return false ;
//	   DocResource dr=docHierarchyManager.getDocResourceById(archiveId);
//	   return dr == null ? false : true;
//   }
   
   public String getPhysicalPath(String logicalPath, String separator,boolean needSub1,int beginIndex){
	   return docHierarchyManager.getPhysicalPathDetail(logicalPath, separator,needSub1,beginIndex);
   }
   private String getTrackIds(Long affairId){
	   String ids = "";
	   if(affairId!=null){
		   List<ColTrackMember> tracks = null;
		   try{
			   tracks= colManager.getColTrackMembers(Long.valueOf(affairId));
		   }catch(Exception e){
			   log.error(e);
		   }
			if(tracks!=null){
				for(ColTrackMember colTrackMember:tracks){
					if("".equals(ids))ids = String.valueOf(colTrackMember.getTrackMemberId());
					else ids += ","+String.valueOf(colTrackMember.getTrackMemberId());
				}
			}
	   }
	   return ids;
   }
    /**
     * 获取一篇公文的全部属性
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView summary(HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        try {
        	User user=CurrentUser.get(); 
        	//summary
        	ModelAndView mav = new ModelAndView("edoc/edocSummary");
        	String s_summaryId = request.getParameter("summaryId");
        	long summaryId = 0L;
        	if(s_summaryId!=null&&!s_summaryId.isEmpty()){
        		summaryId = Long.parseLong(s_summaryId);
        	}
            
        	EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
        	
        	//公文处理意见回显到公文单,排序    
            long flowPermAccout = EdocHelper.getFlowPermAccountId(user.getLoginAccount(), summary, templeteManager);
           //lijl添加返回EdocFormExtendInfo对象,获取意见设置值-----------------------------------State
    		EdocFormExtendInfo edocFormExtendInfo=edocFormManager.getEdocOpinionConfig(summary.getFormId(), flowPermAccout);
    		String[] optionFormatSets=null;
    		String optionType="0";
    		String opinionType="0";
    		if(edocFormExtendInfo!=null&&!"".equals(edocFormExtendInfo)){
    			optionFormatSets = edocFormExtendInfo.getOptionFormatSet().split(",");
    			if("2".equals(optionFormatSets[1])){
    				opinionType = optionFormatSets[1];
    			}
    			optionType=optionFormatSets[0];
    			if(optionFormatSets.length>3 && (!"0".equals(optionFormatSets[3]))){
    				optionType=optionFormatSets[3];
    			}
    		}
            //查找公文单意见元素显示。
    		EdocOpinionDisplayConfig displayConfig = edocFormManager.getEdocOpinionDisplayConfig(summary.getFormId(),flowPermAccout);
    		Map<String,EdocOpinionModel> map1 = edocManager.getEdocOpinion(summary,displayConfig.isOnlyShowLastOpinion(),optionType);
    		Set set=null;
    		String policy=null;
    		if(map1!=null&&!map1.isEmpty()){
    			set=map1.entrySet();
    			if(set!=null&&!set.isEmpty()){
    				Iterator it=set.iterator();
    				while(it.hasNext()){
    					Map.Entry entry = (Map.Entry) it.next();
    					if(entry!=null&&!"".equals(entry)){
    						policy=entry.getKey().toString();
    					}
    				}
    			}
    		}
    		EdocOpinionModel edocOpinionModel=null;
    		if(map1!=null){
    			edocOpinionModel=map1.get(policy);
    		}
    		List<EdocOpinion> opinions=null;
    		if(edocOpinionModel!=null){
    			opinions=edocOpinionModel.getOpinions();
    		}
    		EdocOpinion edocOpinion=null;
    		Affair affair1 =null;
    		String affairState=null;
    		if(opinions!=null){
    			edocOpinion=opinions.get(opinions.size()-1);
    			affair1 = affairManager.getById(edocOpinion.getAffairId());
    			if(affair1!=null&&!"".equals(affair1)){
    				affairState=String.valueOf(affair1.getState());
    			}
    		}
    		
    		//节点类型(shenpi、huitui...)
    		mav.addObject("policy",policy);
    		//是否是退回的状态
    		mav.addObject("affairState",affairState);
    		//设置意见类型的值
    		mav.addObject("optionType",optionType);
    		mav.addObject("opinionType", opinionType);
    		//意见表Id
    		//GOV-3044 公文管理-发文管理-待办，有数据报空指针错误
    		if(edocFormExtendInfo != null)
    		mav.addObject("optionId",edocFormExtendInfo.getId());
    		//lijl添加返回EdocFormExtendInfo对象,获取意见设置值-----------------------------------End
    		
            mav.addObject("summary", summary); 
            mav.addObject("contentRecordId", summary.getEdocBodiesJs());
            mav.addObject("archiveName", edocManager.getShowArchiveNameByArchiveId(summary.getArchiveId()));
            mav.addObject("hasPrePighole", summary.getArchiveId() == null?false:true);
            mav.addObject("fullArchiveName", edocManager.getFullArchiveNameByArchiveId(summary.getArchiveId()));
            Metadata remindMetadata = metadataManager.getMetadata(MetadataNameEnum.common_remind_time);
            Metadata  deadlineMetadata= metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline);
            String remindLabel=remindMetadata.getItemLabel(summary.getAdvanceRemind().toString());
            String deallineLabel=deadlineMetadata.getItemLabel(summary.getDeadline().toString());
            String bounder="com.seeyon.v3x.collaboration.resources.i18n.CollaborationResource";        
            mav.addObject("deallineLabel", ResourceBundleUtil.getString(bounder,deallineLabel));        
            bounder="com.seeyon.v3x.common.resources.i18n.SeeyonCommonResources";
            mav.addObject("remindLabel", ResourceBundleUtil.getString(bounder,remindLabel));        
            //是否允许拟文人修改附件。
            boolean allowUpdateAttachment=EdocSwitchHelper.allowUpdateAttachment();
            mav.addObject("allowUpdateAttachment",allowUpdateAttachment);
            //只查找正文的附件。
            mav.addObject("attachments", attachmentManager.getByReference(summaryId,summaryId));  
            
            mav.addObject("controller", "edocController.do");
            
            mav.addObject("openFrom",request.getParameter("openFrom"))
        	.addObject("lenPotent",request.getParameter("lenPotent"))
        	.addObject("docId",request.getParameter("docId"));
            try{
              	V3xOrgMember member = this.orgManager.getMemberById(user.getId());
              	if(member != null){
              		mav.addObject("extendConfig", member.getProperty("extendConfig"));
              	}
              }catch(Exception e){
              	log.error(e);
              }
            
            //showdial

        	String _affairId = request.getParameter("affairId");
        	Long affairId = null;
        	Affair affair =null;
        	EdocZcdb edocZcdb=null; //暂存待办提醒时间
            
            Long currentNodeOwner = user.getId();
        	try {
        		affairId = new Long(_affairId);
        		affair = affairManager.getById(affairId);
                if(affair != null && !affair.getMemberId().equals(currentNodeOwner)){
                    currentNodeOwner = affair.getMemberId();
                }
                
                //暂存待办提醒时间
                edocZcdb=edocZcdbManager.getEdocZcdbByAffairId(affairId);
                if(edocZcdb!=null){
                	mav.addObject("zcdbTime",edocZcdb.getZcdbTime());
                }
                
        	} catch (Exception ex) {}
//        	long summaryId = Long.parseLong(_summaryId);
//        	EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
        	
        	//ModelAndView mav = new ModelAndView("edoc/showToolBar");
        	
        	mav.addObject("finished", summary.getFinished());
        	
        	String supervise = request.getParameter("supervise");
        	if(Strings.isNotBlank(supervise)){
        		mav.addObject("supervisePanel", supervise);
        	} 
        	
        	boolean hasDiagram = false;
            if(summary != null && summary.getCaseId()!= null)
            	hasDiagram = true;
            
            mav.addObject("hasDiagram", hasDiagram);
        	mav.addObject("hasBody1", summary.getBody(1)!=null);
        	mav.addObject("hasBody2", summary.getBody(2)!=null);
        	EdocBody pb = summary.getBody(EdocBody.EDOC_BODY_PDF_ONE);
        	mav.addObject("firstPDFId", pb!=null ? pb.getContent():"");
        	mav.addObject("processId", summary.getProcessId());
        	mav.addObject("caseId", summary.getCaseId());
        	mav.addObject("archiveFullName", edocManager.getFullArchiveNameByArchiveId(summary.getArchiveId()));
        	if(summary.getCaseId() == null){
        		StringBuilder sb=new StringBuilder();
        		sb.append("公文的CaseId为null: " );
        		if(summary!=null)	sb.append( summary.getId());
        		if(affair!=null)	sb.append(", " + affair.getId());
        		sb.append(", " + user.getName());
        		log.warn(sb.toString());
        	}
        	mav.addObject("edocType", summary.getEdocType());
        	
        	//判断归档文件夹是否存在
        	boolean docResourceExist = docHierarchyManager.docResourceExist(summary.getArchiveId());
        	mav.addObject("isPresPigeonholeFolderExsit",docResourceExist);
        	//如果归档文件夹被删除了，设置summary为未归档。
        	if(!docResourceExist) {
        		summary.setArchiveId(null);
        		summary.setHasArchive(false);
        	}
        	mav.addObject("hasArchive", summary.getHasArchive());
        	mav.addObject("hasSetPigeonholePath", summary.getArchiveId() == null ? false :true);
        	//转发公文：新生成一个待转发的清除了痕迹的公文,产生一个这样的公文的ID。
        	mav.addObject("transmitSendNewEdocId", UUIDLong.longUUID());
        	mav.addObject("trackIds",getTrackIds(affairId));
        	
        	String openFrom=request.getParameter("openFrom");
        	String lenPotents=request.getParameter("lenPotent");
            String lenPotent="0";
            String lenPotentPrint="0";//借阅设置的打印权限
            if(lenPotents!=null && !"".equals(lenPotents))
            {
            	lenPotent=lenPotents.substring(0,1);
            	lenPotentPrint=lenPotents.substring(2,3);
            }        

            String onlySeeContent="false";
            String from = request.getParameter("from");
            if("lenPotent".equals(openFrom) && Byte.toString(com.seeyon.v3x.doc.util.Constants.LENPOTENT_CONTENT).equals(lenPotent))
            {
            	onlySeeContent="true";        	
            }
            mav.addObject("onlySeeContent", onlySeeContent);
            boolean affairCanPrint = false; //事项的节点权限是否包含打印操作
            boolean isSupervisor = false; //是否督办人
        	Map<String, List<String>> actions  = new HashMap<String,List<String>>();
        	if(!"WaiSend".equals(request.getParameter("from"))){ //待发不用判断权限
        		String nodePermissionPolicy = "shenpi";
        		
        		BPMProcess process = ColHelper.getCaseProcess(summary.getProcessId());
        		
        		BPMActivity activity = ColHelper.getBPMActivityByAffair(process, affair);
        		if(affair != null)
        		{
        			if("Pending".equals(request.getParameter("from")))
        			{
        				//是否当前节点的最后一个处理人在preSend中判断
    	        		/*Boolean isMatch = false;
    	        		if(null!=activity&&null!=activity.getSeeyonPolicy()&&null!=activity.getSeeyonPolicy().getId()&&null!=process&&null!=affair&&EdocHelper.isExecuteFinished(process, affair) && !"zhihui".equals(activity.getSeeyonPolicy().getId())){
    	        			isMatch = true;
    	        		}*/
    	        		EdocOpinion tempOpinion=edocManager.findBySummaryIdAndAffairId(summaryId, affair.getId());
    	        		mav.addObject("tempOpinion", tempOpinion);
    	        		if(tempOpinion!=null)
    	        		{
    	        			mav.addObject("attachmentsOpinion", attachmentManager.getByReference(summaryId,tempOpinion.getId()));
    	        		}
            			//mav.addObject("isMatch", isMatch);
            			//检查是否有公文发起权----只检查有没有发文的权利
            	        boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
            	        mav.addObject("isEdocCreateRole",isEdocCreateRole);
        			}
        			
        			if(activity != null){ //发起者不需要
        				String currentNodeId = activity.getId();
        				mav.addObject("currentNodeId", currentNodeId);
        			}
        			
        			//催办按钮只有在已发事项中才能显示
        			
    	            if(affair.getSubObjectId() == null 
    	            		&& affair.getState()==StateEnum.col_sent.getKey()
    	            		&& user.getId() == affair.getSenderId())
        				mav.addObject("showHastenButton", "true");
    	            
        				
    	            //得到当前处理权限录入意见的显示位置
    	            if(activity != null){
    	            	nodePermissionPolicy = activity.getSeeyonPolicy().getId();
    	            }
        			String disPosition=edocFormManager.getOpinionLocation(summary.getFormId(),EdocHelper.getFlowPermAccountId(summary, user.getLoginAccount(), templeteManager)).get(nodePermissionPolicy);
        			if(disPosition==null){disPosition=nodePermissionPolicy;}
        			else{
        				String[] dis = disPosition.split("[_]");
        				disPosition = dis[0];
        			}
        			mav.addObject("disPosition", disPosition);
        			mav.addObject("affair", affair); 
        		}    		
        		MetadataNameEnum edocTypeEnum=EdocUtil.getEdocMetadataNameEnum(summary.getEdocType());
        		MetadataItem tempMitem=null;
//        		获取节点权限，如果是自由流程取发起人所在单位的节点权限，模板取模板所在单位节点权限
        		//Long accountId=orgManager.getMemberById(summary.getStartUserId()).getOrgAccountId();
        		Long senderId = summary.getStartUserId();
    	        V3xOrgMember sender = orgManager.getMemberById(senderId);
    	        
    	        Long flowPermAccountId = EdocHelper.getFlowPermAccountId(summary, sender.getOrgAccountId(), templeteManager);
    	        FlowPerm fpm = new FlowPerm();
        		try{    			
        			fpm=flowPermManager.getFlowPerm(edocTypeEnum.name(), nodePermissionPolicy, flowPermAccountId);
        			
        			if(null!=fpm){
        				mav.addObject("opinionPolicy", fpm.getNodePolicy().getOpinionPolicy());
        				mav.addObject("attitudes", fpm.getNodePolicy().getAttitude());
        				if(fpm.getType()==com.seeyon.v3x.flowperm.util.Constants.F_type_system){
        					tempMitem=metadataManager.getMetadataItem(edocTypeEnum, nodePermissionPolicy);
        				}
        			}
        			
        		}catch(Exception e)
        		{    			
        			log.error("",e);
        		}
        		mav.addObject("nodePermissionPolicy", tempMitem);
        		
        		mav.addObject("nodePermissionPolicyKey",nodePermissionPolicy);
                
                
                Hashtable<String, String> elementBoundFlowPerm = edocFormManager.getOpinionLocation(summary.getFormId(), flowPermAccountId);
                String element = elementBoundFlowPerm.get(nodePermissionPolicy);
                mav.addObject("position",Strings.isBlank(element)?"":element.substring(0, element.indexOf("_")));
        	
                actions = permissionManager.getActionMap(edocTypeEnum.name(), nodePermissionPolicy, flowPermAccountId);
        		List<String> baseActions = actions.get("basic");
        		if(baseActions == null){
        			log.error("edocController.summary : baseActions is null! [edocTypeEnum.name():"+edocTypeEnum.name()+" nodePermissionPolicy:"+nodePermissionPolicy +" flowPermAccountId:"+flowPermAccountId+" summary.id:"+summary.getId());
        		}
        		//检查归档策略，归档只能在封发节点出现，流程结束后才可以归档
        		//baseActions=EdocHelper.checkPerm(baseActions,nodePermissionPolicy);
    	        List<String> advancedActions = actions.get("advanced");
    	        List<String> commonActions = actions.get("common");
    	        
    			// 公文所属单位的公文收发员
    			List<V3xOrgMember> memberList = new ArrayList<V3xOrgMember>();
    			if (("fengfa".equals(nodePermissionPolicy))
    					|| (baseActions!=null && baseActions.contains("EdocExchangeType"))) {
    				// 封发节点或者是具有【交换类型】节点权限
    				memberList = EdocRoleHelper.getAccountExchangeUsers(summary
    						.getOrgAccountId());
    				mav.addObject("memberList", memberList);
    			}

    	        if(baseActions!=null && baseActions.contains("Print")) affairCanPrint = true;
    	        
    	        
    	        //判断是否能进行归档操作：
    	        boolean canArchive = false;
    	        if(baseActions!=null && baseActions.contains("Archive") && !summary.getHasArchive()){  //封发及自定义节点可以进行归档操作
//    	        	if(summary.getEdocType() == EdocEnum.edocType.sendEdoc.ordinal()){
//    			        if("fengfa".equals(nodePermissionPolicy)) canArchive = true;
//    			        if(fpm.getType()!=com.seeyon.v3x.flowperm.util.Constants.F_type_system) canArchive = true;
//    	        	}else{
    	        		 canArchive = true; 
    	        	//}
    	        }
    	        //把常用操作和高级操作合并到一个list中，用于控制显示8个后，其余的显示到更多中
               List<String> totalActions=new ArrayList<String>(); 
               //修复bug GOV-3039 公文管理-收文管理-待阅，点击一条公文，弹出null
               if(commonActions != null)
               totalActions.addAll(commonActions);
               if(advancedActions != null)
               totalActions.addAll(advancedActions);
               if(totalActions.contains("JointSign")){ //当前会签
            	   totalActions.remove("JointSign");
               }
               if(totalActions.contains("UpdateForm")){ //修改文单
            	   totalActions.remove("UpdateForm");
               }
               if(totalActions.contains("moreSign")){  //多级会签
            	   totalActions.remove("moreSign");
               }
               if(totalActions.contains("Return")){  //回退
            	   totalActions.remove("Return");
               }
               if(totalActions.contains("Terminate")){ //终止
            	   totalActions.remove("Terminate");
               }
               
               int adButtonCount=7; //高级操作中，按钮数初始化为7。7个要包括基本操作的跟踪和归档，所以按钮数要判断这两个操作有没有
               if(baseActions.contains("Track")){ //跟踪
            	   adButtonCount--;
               }
               if(baseActions.contains("Archive")){ //归档
            	   adButtonCount--;
               }
    	        
    	        mav.addObject("canArchive", canArchive);
    	        mav.addObject("baseActions", baseActions);
    	        mav.addObject("advancedActions", advancedActions);
    	        mav.addObject("commonActions", commonActions);
    	        mav.addObject("totalActions", totalActions);
    	        mav.addObject("adButtonCount", adButtonCount);
        	}

        	Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        	Metadata comMetadata = metadataManager.getMetadata(MetadataNameEnum.common_remind_time);
            Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
            colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
            Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
            colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
        	
        	mav.addObject("comMetadata", comMetadata);
        	mav.addObject("colMetadata", colMetadata);
        	mav.addObject("summary", summary);
        	mav.addObject("isShowButton", false);
        	
        	mav.addObject("appTypeName",EdocEnum.getEdocAppName(summary.getEdocType()));
        	
        	mav.addObject("curUser", CurrentUser.get());
        	
        	//得到公文发起人
        	long edocSendUserId=summary.getStartUserId();
        	V3xOrgMember edocSendMember=orgManager.getMemberById(edocSendUserId);
        	mav.addObject("edocSendMember", edocSendMember);
        	
        	mav.addObject("controller", "edocController.do");
        
        	// 督办开始
        	Set<String> idSets = new HashSet<String>();
    		StringBuffer supervisorId = new StringBuffer(); // supervisorId : all the ids of supervise detail
    		StringBuffer tempIds = new StringBuffer(); // tempIds : all the ids of superviseTemplate
    		ColSuperviseDetail detail = this.colSuperviseManager.getSupervise(Constant.superviseType.edoc.ordinal(), summaryId);
    		if(detail != null) {
    			Set<ColSupervisor> supervisors = detail.getColSupervisors();
    			Set<Long> userSuper = new HashSet<Long>();
    			for(ColSupervisor supervisor:supervisors){
    				userSuper.add(supervisor.getSupervisorId().longValue());
    				idSets.add(supervisor.getSupervisorId().toString());
    			}
    			if(null!=summary && null!=summary.getTempleteId()){
    				ColSuperviseDetail tempDetail = colSuperviseManager.getSupervise(Constant.superviseType.template.ordinal(),summary.getTempleteId());
    				if(null!=tempDetail){
    					Set<ColSupervisor> tempVisors = tempDetail.getColSupervisors();
    					for(ColSupervisor ts : tempVisors){
    						if(userSuper.contains(ts.getSupervisorId())){
    							idSets.add(ts.getSupervisorId().toString());
    							tempIds.append(ts.getSupervisorId().toString() + ",");
    						}
    					}
    					
    					List<SuperviseTemplateRole> roleList = colSuperviseManager.findSuperviseRoleByTemplateId(summary.getTempleteId());
    					V3xOrgRole orgRole = null;
    					V3xOrgMember starter = orgManager.getMemberById(summary.getStartUserId());
    					if(null!=starter){
    					for (SuperviseTemplateRole role : roleList) {
    						if (null == role.getRole() || "".equals(role.getRole())) {
    							continue;
    						}
    						if (role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase())) {
    							if(userSuper.contains(starter.getId())){
    								idSets.add(String.valueOf(starter.getId()));
    								tempIds.append(starter.getId() + ",");
    							}
    						}
    						if (role.getRole().toLowerCase().equals(
    										V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase() + V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER.toLowerCase())) {
    							orgRole = orgManager.getRoleByName(V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER, starter.getOrgAccountId());
    							if (null != orgRole) {
    								List<V3xOrgDepartment> depList = orgManager
    										.getDepartmentsByUser(starter.getId());
    								for (V3xOrgDepartment dep : depList) {
    									List<V3xOrgMember> managerList = orgManager.getMemberByRole(V3xOrgEntity.ROLE_BOND_DEPARTMENT, dep.getId(), orgRole.getId());
    									for (V3xOrgMember mem : managerList) {
    										if(userSuper.contains(mem.getId())){
    											idSets.add(mem.getId().toString());
    											tempIds.append(mem.getId() + ",");
    										}
    									}
    								}
    							}
    						}
    						if (role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase() + V3xOrgEntity.ORGENT_META_KEY_SUPERDEPMANAGER.toLowerCase())) {
    							orgRole = orgManager.getRoleByName(V3xOrgEntity.ORGENT_META_KEY_SUPERDEPMANAGER, starter.getOrgAccountId());
    							if (null != orgRole) {
    								List<V3xOrgDepartment> depList = orgManager.getDepartmentsByUser(starter.getId());
    								for (V3xOrgDepartment dep : depList) {
    									List<V3xOrgMember> superManagerList = orgManager.getMemberByRole(V3xOrgEntity.ROLE_BOND_DEPARTMENT, dep.getId(), orgRole.getId());
    									for (V3xOrgMember mem : superManagerList) {
    										if(userSuper.contains(mem.getId())){
    											idSets.add(mem.getId().toString());
    											tempIds.append(mem.getId() + ",");
    										}
    									}
    								}
    							}
    						}
    					}
    					
    				}
    				}
    			}

    			for(String id : idSets){
    				supervisorId.append(id+",");					
    			}
    			if(supervisorId.length()>0){
    				mav.addObject("supervisorId", supervisorId.substring(0, supervisorId.length()-1));
    			}
    			mav.addObject("superviseId", detail.getId());
    			mav.addObject("supervisors", detail.getSupervisors());
    			mav.addObject("superviseTitle", detail.getTitle());
    			mav.addObject("awakeDate", Datetimes.format(detail.getAwakeDate(), Datetimes.datetimeWithoutSecondStyle));
    			mav.addObject("superviseTitle", detail.getTitle());
    			mav.addObject("count", idSets.size());
    			if(idSets.contains(String.valueOf(user.getId()))){
    				mav.addObject("isSupervis", true);
    				isSupervisor = true;
    			}
    		
            	mav.addObject("openModal", request.getParameter("openModal")); 
            	mav.addObject("bean", detail); 
    			if(tempIds.length()>0){
    				String unCancelledVisor = tempIds.substring(0, tempIds.length()-1);
    				mav.addObject("unCancelledVisor", unCancelledVisor);
    				mav.addObject("sVisorsFromTemplate", "true");//公文调用的督办模板是否设置了督办人
    			}
    		}
    	
        	
        	boolean templateFlag = false;
        	if(summary.getTempleteId() != null) templateFlag = true;
        	
        	//分支 开始
            if(summary.getTempleteId()!=null) {
            	List<ColBranch> branchs = this.templeteManager.getBranchsByTemplateId(summary.getTempleteId(),ApplicationCategoryEnum.edoc.ordinal());
            	if(branchs != null) {
                    //显示分支条件使用流程中保留的，如果为空使用模板中的
            		branchs = EdocHelper.updateBranchByProcess(summary.getProcessId(),branchs);
            		mav.addObject("branchs", branchs);
            		List<V3xOrgEntity> entities = this.orgManager.getUserDomain(currentNodeOwner, V3xOrgEntity.VIRTUAL_ACCOUNT_ID, V3xOrgEntity.ORGENT_TYPE_TEAM);
            		if(entities != null && !entities.isEmpty()){
            			V3xOrgTeam team = null;
            			List<V3xOrgTeam> teams = new ArrayList<V3xOrgTeam>();
            			for(V3xOrgEntity entity:entities){
            				team = (V3xOrgTeam) entity;
            				if(team != null && team.getAllMembers() != null && team.getAllMembers().contains(currentNodeOwner)){
            					teams.add(team);
            				}
            			}
            			mav.addObject("teams", teams);
            		}
            		V3xOrgMember mem = orgManager.getMemberById(currentNodeOwner);
            		List<MemberPost> secondPosts = mem.getSecond_post();
            		mav.addObject("secondPosts", secondPosts);
            		mem = orgManager.getMemberById(summary.getStartUserId());
            		mav.addObject("startTeams", this.orgManager.getUserDomain(mem.getId(), V3xOrgEntity.VIRTUAL_ACCOUNT_ID, V3xOrgEntity.ORGENT_TYPE_TEAM));
            		mav.addObject("startSecondPosts", mem.getSecond_post());
                }
            	
            	templateFlag = true;
            }
        	//分支 结束
            //文单打印权限的控制 -------------
            /**关于openFrom：从公文档案库传递过来的时候值为edocDocLib,普通文档库（包括共享）为docLib,借阅的时候为lenPotent
             * 从文档相关消息框弹出来的时候为"null"，暂时只发现这几个值，但是每种情况都会传递参数lenPotent，所以这里判断文单打印权限的时候使用lenPotent来判断*/
            String printEdocTable="";
            if("true".equals(request.getParameter("isLibOwner"))){  //文档库相关
            	printEdocTable="true";
            }else if(Strings.isNotBlank(lenPotents)){
            	printEdocTable = "0".equals(lenPotentPrint) ? "false" : "true";
            }else if("glwd".equals(openFrom)){//从关联文档点击进来的，都不可以打印
            	printEdocTable="false";
            }else if("sended".equals(from) || "WaitSend".equals(from)) { //已发送和保存待发
            	printEdocTable="true";
            }else if(isSupervisor){//督办节点都能打印
            	printEdocTable = "true";
            }else {
            	printEdocTable = affairCanPrint ? "true" : "false";
            }
            mav.addObject("printEdocTable", printEdocTable);
            //-----

            
        	Map<String,List<String>> map = parse2WebActionList(actions, "true".equals(printEdocTable)?true:false);
            mav.addObject("toolBarActions", map.get("toolBar"));
            mav.addObject("moreActions", map.get("more") );
        	mav.addObject("affairId",_affairId)  ;
        	mav.addObject("templateFlag", templateFlag);
        	mav.addObject("from", request.getParameter("from"));
        	mav.addObject("newPdfIdFirst", UUIDLong.longUUID());
        	mav.addObject("newPdfIdSecond", UUIDLong.longUUID());
        	if(summary.getFirstBody()!=null && "OfficeWord".equals(summary.getFirstBody().getContentType())) {
            	mav.addObject("firstBodyContent", summary.getFirstBody().getContent());	
            }
        	//程炯 太原市政府项目 2012-7-26 查出请示卡内容
        	if(summary.getEdocType() == EdocEnum.edocType.signReport.ordinal()){
        		ConfigItem edocFormItem = configManager.getConfigItem(SHANG_KA, String.valueOf(summary.getId()),user.getAccountId());
        		if(!("".equals(edocFormItem))&&null != edocFormItem){
        			String result = edocFormItem.getExtConfigValue();
        			//result =Strings.toHTML(result, false);
        			mav.addObject("cardInfo", result);
        		}
        	}
        	return mav;
        }
        catch (Exception e) {
        	log.error("",e);
        	PrintWriter out = response.getWriter();        	
        	//super.printV3XJS(out);        	
        	out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(e.getMessage()) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"true\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("");
        	out.println("</script>");
        	
        	return null;
		}
    
    }
    
    private ConfigItem getNewConfigItem(String item,String value,Long accountId)
	{
		ConfigItem edocItem=new ConfigItem();
		edocItem.setIdIfNew();
		edocItem.setConfigCategory(SHANG_KA);
		edocItem.setConfigItem(item);
		edocItem.setExtConfigValue(value);
		edocItem.setOrgAccountId(accountId);
		edocItem.setCreateDate(new Timestamp(new Date().getTime()));
		return edocItem;
	}
    
    public ModelAndView superviseDiagram(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView("edoc/edocDiagramSupervise");
        String s_summaryId = request.getParameter("summaryId");
        long summaryId = Long.parseLong(s_summaryId);
        ColSuperviseDetail detail = edocSuperviseManager.getSuperviseBySummaryId(summaryId);
        if(detail!=null){
        	boolean isSupervis = false;
        	String supervisors= detail.getSupervisors();
        	String []supervisorsArry = supervisors.split("、");
        	for (String str : supervisorsArry) {
				if(str.equals(CurrentUser.get().getName())){
            		isSupervis=true;
            		break;
				}
			}
        	
        	EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
        	modelAndView.addObject("finished", summary.getFinished());
            modelAndView.addObject("isSupervis", isSupervis); 
        	modelAndView.addObject("bean", detail); 
        }
        modelAndView.addObject("summaryId", s_summaryId); 
    	return modelAndView;
    }
    
    private Map<String, List<String>>  parse2WebActionList(Map<String, List<String>> actions,boolean isEdocFormCanPrint){
    	
        List<String> advancedActions = actions.get("advanced");
        List<String> commonActions = actions.get("common");
        Map<String, List<String>> map =new HashMap<String, List<String>>() ;
        int toolBarShowSize = 8;//页面工具条显示的按钮数
//        同意排序，工具条显示8个，其余的显示到高级操作中       
//        List<String> all = new ArrayList<String>();
//        if(commonActions!=null) all.addAll(commonActions);
//        if(advancedActions!=null)  all.addAll(advancedActions);
//        all.add("edocFormPrint");
//        all.add("logDetail");
//        int allSize = all.size();
//        map.put("toolBar", allSize>=toolBarShowSize ? all.subList(0,toolBarShowSize):all.subList(0,allSize));
//        map.put("more", all.size()>toolBarShowSize ? all.subList(toolBarShowSize,allSize):null);
//     
        List<String> more = new ArrayList<String>();
        if(commonActions != null){
	        if(commonActions.size()<=toolBarShowSize){
	        	map.put("toolBar", commonActions);
	        }else{
	        	map.put("toolBar", commonActions.subList(0, toolBarShowSize));
	        	more.addAll(commonActions.subList(toolBarShowSize,commonActions.size()));
	        }
        }else{
        	map.put("toolBar", null);
        }
        
        if(advancedActions != null) more.addAll(advancedActions);
        
        more.add("edocFormPrint");
        more.add("logDetail");
        
        map.put("more", more);
        return map;
    }

//   public ModelAndView showDiagram(HttpServletRequest request,HttpServletResponse response) throws Exception 
//    {
//    	User user = CurrentUser.get();
//    	String _summaryId = request.getParameter("summaryId");
//    	String _affairId = request.getParameter("affairId");
//    	Long affairId = null;
//    	Affair affair =null;
//        
//        Long currentNodeOwner = user.getId();
//    	try {
//    		affairId = new Long(_affairId);
//    		affair = affairManager.getById(affairId);
//            if(affair != null && !affair.getMemberId().equals(currentNodeOwner)){
//                currentNodeOwner = affair.getMemberId();
//            }
//    	} catch (Exception ex) {}
//    	long summaryId = Long.parseLong(_summaryId);
//    	EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
//    	
//    	ModelAndView mav = new ModelAndView("edoc/showDiagram");
//    	
//    	mav.addObject("finished", summary.getFinished());
//    	
//    	String supervise = request.getParameter("supervise");
//    	if(Strings.isNotBlank(supervise)){
//    		mav.addObject("supervisePanel", supervise);
//    	}
//    	
//    	boolean hasDiagram = false;
//        if(summary != null && summary.getCaseId()!= null)
//        	hasDiagram = true;
//        
//        mav.addObject("hasDiagram", hasDiagram);
//    	mav.addObject("hasBody1", summary.getBody(1)!=null);
//    	mav.addObject("hasBody2", summary.getBody(2)!=null);
//    	mav.addObject("processId", summary.getProcessId());
//    	mav.addObject("caseId", summary.getCaseId());
//    	mav.addObject("archiveFullName", edocManager.getFullArchiveNameByArchiveId(summary.getArchiveId()));
//    	if(summary.getCaseId() == null){
//    		StringBuilder sb=new StringBuilder();
//    		sb.append("公文的CaseId为null: " );
//    		if(summary!=null)	sb.append( summary.getId());
//    		if(affair!=null)	sb.append(", " + affair.getId());
//    		sb.append(", " + user.getName());
//    		log.warn(sb.toString());
//    	}
//    	mav.addObject("edocType", summary.getEdocType());
//    	mav.addObject("hasArchive", summary.getHasArchive());
//    	mav.addObject("isPresPigeonholeFolderExsit",docHierarchyManager.docResourceExist(summary.getArchiveId()));
//    	mav.addObject("hasSetPigeonholePath", summary.getArchiveId() == null ? false :true);
//    	if(summary.getArchiveId() != null && !docHierarchyManager.docResourceExist(summary.getArchiveId())) summary.setArchiveId(null);
//    	//    	转发公文：新生成一个待转发的清除了痕迹的公文,产生一个这样的公文的ID。
//    	mav.addObject("transmitSendNewEdocId", UUIDLong.longUUID());
//    	String openFrom=request.getParameter("openFrom");
//    	String lenPotents=request.getParameter("lenPotent");
//        String lenPotent="0";
//        String lenPotentPrint="0";//借阅设置的打印权限
//        if(lenPotents!=null && !"".equals(lenPotents))
//        {
//        	lenPotent=lenPotents.substring(0,1);
//        	lenPotentPrint=lenPotents.substring(2,3);
//        }        
//
//        String onlySeeContent="false";
//        String from = request.getParameter("from");
//        if("lenPotent".equals(openFrom) && Byte.toString(com.seeyon.v3x.doc.util.Constants.LENPOTENT_CONTENT).equals(lenPotent))
//        {
//        	onlySeeContent="true";        	
//        }
//        mav.addObject("onlySeeContent", onlySeeContent);
//        boolean affairCanPrint = false; //事项的节点权限是否包含打印操作
//        boolean isSupervisor = false; //是否督办人
//    	if(!"WaiSend".equals(request.getParameter("from"))){ //待发不用判断权限
//    		String nodePermissionPolicy = "shenpi";
//    		
//    		BPMProcess process = ColHelper.getCaseProcess(summary.getProcessId());
//    		
//    		BPMActivity activity = ColHelper.getBPMActivityByAffair(process, affair);
//    		if(affairId != null)
//    		{
//    			if("Pending".equals(request.getParameter("from")))
//    			{
//    				//是否当前节点的最后一个处理人在preSend中判断
//	        		/*Boolean isMatch = false;
//	        		if(null!=activity&&null!=activity.getSeeyonPolicy()&&null!=activity.getSeeyonPolicy().getId()&&null!=process&&null!=affair&&EdocHelper.isExecuteFinished(process, affair) && !"zhihui".equals(activity.getSeeyonPolicy().getId())){
//	        			isMatch = true;
//	        		}*/
//	        		EdocOpinion tempOpinion=edocManager.findBySummaryIdAndAffairId(summaryId, affairId);
//	        		mav.addObject("tempOpinion", tempOpinion);
//	        		if(tempOpinion!=null)
//	        		{
//	        			mav.addObject("attachments", attachmentManager.getByReference(summaryId,tempOpinion.getId()));
//	        		}
//        			//mav.addObject("isMatch", isMatch);
//        			//检查是否有公文发起权----只检查有没有发文的权利
//        	        boolean isEdocCreateRole=EdocRoleHelper.isEdocCreateRole(EdocEnum.edocType.sendEdoc.ordinal());
//        	        mav.addObject("isEdocCreateRole",isEdocCreateRole);
//    			}
//    			
//    			if(activity != null){ //发起者不需要
//    				String currentNodeId = activity.getId();
//    				mav.addObject("currentNodeId", currentNodeId);
//    			}
//    			
//    			//催办按钮只有在已发事项中才能显示
//    			
//	            if(affair.getSubObjectId() == null 
//	            		&& affair.getState()==StateEnum.col_sent.getKey()
//	            		&& user.getId() == affair.getSenderId())
//    				mav.addObject("showHastenButton", "true");
//	            
//    				
//	            //得到当前处理权限录入意见的显示位置
//	            if(activity != null){
//	            	nodePermissionPolicy = activity.getSeeyonPolicy().getId();
//	            }
//    			String disPosition=edocFormManager.getOpinionLocation(summary.getFormId(),EdocHelper.getFlowPermAccountId(summary, user.getLoginAccount(), templeteManager)).get(nodePermissionPolicy);
//    			if(disPosition==null){disPosition=nodePermissionPolicy;}
//    			mav.addObject("disPosition", disPosition);
//    			mav.addObject("affair", affair);
//    		}    		
//    		MetadataNameEnum edocTypeEnum=EdocUtil.getEdocMetadataNameEnum(summary.getEdocType());
//    		MetadataItem tempMitem=null;
////    		获取节点权限，如果是自由流程取发起人所在单位的节点权限，模板取模板所在单位节点权限
//    		//Long accountId=orgManager.getMemberById(summary.getStartUserId()).getOrgAccountId();
//    		Long senderId = summary.getStartUserId();
//	        V3xOrgMember sender = orgManager.getMemberById(senderId);
//	        
//	        Long flowPermAccountId = EdocHelper.getFlowPermAccountId(summary, sender.getOrgAccountId(), templeteManager);
//	        FlowPerm fpm = new FlowPerm();
//    		try{    			
//    			fpm=flowPermManager.getFlowPerm(edocTypeEnum.name(), nodePermissionPolicy, flowPermAccountId);
//    			
//    			if(null!=fpm){
//    				mav.addObject("opinionPolicy", fpm.getNodePolicy().getOpinionPolicy());
//    				mav.addObject("attitudes", fpm.getNodePolicy().getAttitude());
//    				if(fpm.getType()==com.seeyon.v3x.flowperm.util.Constants.F_type_system){
//    					tempMitem=metadataManager.getMetadataItem(edocTypeEnum, nodePermissionPolicy);
//    				}
//    			}
//    			
//    		}catch(Exception e)
//    		{    			
//    			log.error("",e);
//    		}
//    		mav.addObject("nodePermissionPolicy", tempMitem);
//    		
//    		mav.addObject("nodePermissionPolicyKey",nodePermissionPolicy);
//    		
//    		Map<String, List<String>> actions = permissionManager.getActionMap(edocTypeEnum.name(), nodePermissionPolicy, flowPermAccountId);
//    		List<String> baseActions = actions.get("basic");
//    		//检查归档策略，归档只能在封发节点出现，流程结束后才可以归档
//    		//baseActions=EdocHelper.checkPerm(baseActions,nodePermissionPolicy);
//	        List<String> advancedActions = actions.get("advanced");
//	        List<String> commonActions = actions.get("common");
//	        
//			// 公文所属单位的公文收发员
//			List<V3xOrgMember> memberList = new ArrayList<V3xOrgMember>();
//			if (("fengfa".equals(nodePermissionPolicy))
//					|| (baseActions.contains("EdocExchangeType"))) {
//				// 封发节点或者是具有【交换类型】节点权限
//				memberList = EdocRoleHelper.getAccountExchangeUsers(summary
//						.getOrgAccountId());
//				mav.addObject("memberList", memberList);
//			}
//
//	        if(baseActions.contains("Print")) affairCanPrint = true;
//	        
//	        
//	        //判断是否能进行归档操作：
//	        boolean canArchive = false;
//	        if(baseActions.contains("Archive") && !summary.getHasArchive()){  //封发及自定义节点可以进行归档操作
////	        	if(summary.getEdocType() == EdocEnum.edocType.sendEdoc.ordinal()){
////			        if("fengfa".equals(nodePermissionPolicy)) canArchive = true;
////			        if(fpm.getType()!=com.seeyon.v3x.flowperm.util.Constants.F_type_system) canArchive = true;
////	        	}else{
//	        		 canArchive = true; 
//	        	//}
//	        }
//	        mav.addObject("canArchive", canArchive);
//	        mav.addObject("baseActions", baseActions);
//	        mav.addObject("advancedActions", advancedActions);
//	        mav.addObject("commonActions", commonActions);
//    	}
//
//    	Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
//    	Metadata comMetadata = metadataManager.getMetadata(MetadataNameEnum.common_remind_time);
//        Metadata attitude = metadataManager.getMetadata(MetadataNameEnum.collaboration_attitude); //处理意见 attitude
//        colMetadata.put(MetadataNameEnum.collaboration_attitude.toString(), attitude);
//        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
//        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);   
//    	
//    	mav.addObject("comMetadata", comMetadata);
//    	mav.addObject("colMetadata", colMetadata);
//    	mav.addObject("summary", summary);
//    	mav.addObject("isShowButton", false);
//    	
//    	mav.addObject("appTypeName",EdocEnum.getEdocAppName(summary.getEdocType()));
//    	
//    	mav.addObject("curUser", CurrentUser.get());
//    	
//    	//得到公文发起人
//    	long edocSendUserId=summary.getStartUserId();
//    	V3xOrgMember edocSendMember=orgManager.getMemberById(edocSendUserId);
//    	mav.addObject("edocSendMember", edocSendMember);
//    	
//    	mav.addObject("controller", "edocController.do");
//    
//    	// 督办开始
//    	Set<String> idSets = new HashSet<String>();
//		StringBuffer supervisorId = new StringBuffer(); // supervisorId : all the ids of supervise detail
//		StringBuffer tempIds = new StringBuffer(); // tempIds : all the ids of superviseTemplate
//		ColSuperviseDetail detail = this.colSuperviseManager.getSupervise(Constant.superviseType.edoc.ordinal(), summaryId);
//		if(detail != null) {
//			Set<ColSupervisor> supervisors = detail.getColSupervisors();
//			Set<Long> userSuper = new HashSet<Long>();
//			for(ColSupervisor supervisor:supervisors){
//				userSuper.add(supervisor.getSupervisorId().longValue());
//				idSets.add(supervisor.getSupervisorId().toString());
//			}
//			if(null!=summary && null!=summary.getTempleteId()){
//				ColSuperviseDetail tempDetail = colSuperviseManager.getSupervise(Constant.superviseType.template.ordinal(),summary.getTempleteId());
//				if(null!=tempDetail){
//					Set<ColSupervisor> tempVisors = tempDetail.getColSupervisors();
//					for(ColSupervisor ts : tempVisors){
//						if(userSuper.contains(ts.getSupervisorId())){
//							idSets.add(ts.getSupervisorId().toString());
//							tempIds.append(ts.getSupervisorId().toString() + ",");
//						}
//					}
//					
//					List<SuperviseTemplateRole> roleList = colSuperviseManager.findSuperviseRoleByTemplateId(summary.getTempleteId());
//					V3xOrgRole orgRole = null;
//					V3xOrgMember starter = orgManager.getMemberById(summary.getStartUserId());
//					if(null!=starter){
//					for (SuperviseTemplateRole role : roleList) {
//						if (null == role.getRole() || "".equals(role.getRole())) {
//							continue;
//						}
//						if (role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase())) {
//							if(userSuper.contains(starter.getId())){
//								idSets.add(String.valueOf(starter.getId()));
//								tempIds.append(starter.getId() + ",");
//							}
//						}
//						if (role.getRole().toLowerCase().equals(
//										V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase() + V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER.toLowerCase())) {
//							orgRole = orgManager.getRoleByName(V3xOrgEntity.ORGENT_META_KEY_DEPMANAGER, starter.getOrgAccountId());
//							if (null != orgRole) {
//								List<V3xOrgDepartment> depList = orgManager
//										.getDepartmentsByUser(starter.getId());
//								for (V3xOrgDepartment dep : depList) {
//									List<V3xOrgMember> managerList = orgManager.getMemberByRole(V3xOrgEntity.ROLE_BOND_DEPARTMENT, dep.getId(), orgRole.getId());
//									for (V3xOrgMember mem : managerList) {
//										if(userSuper.contains(mem.getId())){
//											idSets.add(mem.getId().toString());
//											tempIds.append(mem.getId() + ",");
//										}
//									}
//								}
//							}
//						}
//						if (role.getRole().toLowerCase().equals(V3xOrgEntity.ORGENT_META_KEY_SEDNER.toLowerCase() + V3xOrgEntity.ORGENT_META_KEY_SUPERDEPMANAGER.toLowerCase())) {
//							orgRole = orgManager.getRoleByName(V3xOrgEntity.ORGENT_META_KEY_SUPERDEPMANAGER, starter.getOrgAccountId());
//							if (null != orgRole) {
//								List<V3xOrgDepartment> depList = orgManager.getDepartmentsByUser(starter.getId());
//								for (V3xOrgDepartment dep : depList) {
//									List<V3xOrgMember> superManagerList = orgManager.getMemberByRole(V3xOrgEntity.ROLE_BOND_DEPARTMENT, dep.getId(), orgRole.getId());
//									for (V3xOrgMember mem : superManagerList) {
//										if(userSuper.contains(mem.getId())){
//											idSets.add(mem.getId().toString());
//											tempIds.append(mem.getId() + ",");
//										}
//									}
//								}
//							}
//						}
//					}
//					
//				}
//				}
//			}
//
//			for(String id : idSets){
//				supervisorId.append(id+",");					
//			}
//			if(supervisorId.length()>0){
//				mav.addObject("supervisorId", supervisorId.substring(0, supervisorId.length()-1));
//			}
//			mav.addObject("superviseId", detail.getId());
//			mav.addObject("supervisors", detail.getSupervisors());
//			mav.addObject("superviseTitle", detail.getTitle());
//			mav.addObject("awakeDate", Datetimes.format(detail.getAwakeDate(), Datetimes.dateStyle));
//			mav.addObject("superviseTitle", detail.getTitle());
//			mav.addObject("count", idSets.size());
//			if(idSets.contains(String.valueOf(user.getId()))){
//				mav.addObject("isSupervis", true);
//				isSupervisor = true;
//			}
//		
//        	mav.addObject("openModal", request.getParameter("openModal")); 
//        	mav.addObject("bean", detail); 
//			if(tempIds.length()>0){
//				String unCancelledVisor = tempIds.substring(0, tempIds.length()-1);
//				mav.addObject("unCancelledVisor", unCancelledVisor);
//				mav.addObject("sVisorsFromTemplate", "true");//公文调用的督办模板是否设置了督办人
//			}
//		}
//	
//    	
//    	boolean templateFlag = false;
//    	if(summary.getTempleteId() != null) templateFlag = true;
//    	
//    	//分支 开始
//        if(summary.getTempleteId()!=null) {
//        	List<ColBranch> branchs = this.templeteManager.getBranchsByTemplateId(summary.getTempleteId(),ApplicationCategoryEnum.edoc.ordinal());
//        	mav.addObject("branchs", branchs);
//        	if(branchs != null) {
//                //显示分支条件使用流程中保留的，如果为空使用模板中的
//        		EdocHelper.updateBranchByProcess(summary.getProcessId(),branchs);
//        		List<V3xOrgEntity> entities = this.orgManager.getUserDomain(currentNodeOwner, V3xOrgEntity.VIRTUAL_ACCOUNT_ID, V3xOrgEntity.ORGENT_TYPE_TEAM);
//        		if(entities != null && !entities.isEmpty()){
//        			V3xOrgTeam team = null;
//        			List<V3xOrgTeam> teams = new ArrayList<V3xOrgTeam>();
//        			for(V3xOrgEntity entity:entities){
//        				team = (V3xOrgTeam) entity;
//        				if(team != null && team.getAllMembers() != null && team.getAllMembers().contains(currentNodeOwner)){
//        					teams.add(team);
//        				}
//        			}
//        			mav.addObject("teams", teams);
//        		}
//        		V3xOrgMember mem = orgManager.getMemberById(currentNodeOwner);
//        		List<MemberPost> secondPosts = mem.getSecond_post();
//        		mav.addObject("secondPosts", secondPosts);
//        		mem = orgManager.getMemberById(summary.getStartUserId());
//        		mav.addObject("startTeams", this.orgManager.getUserDomain(mem.getId(), V3xOrgEntity.VIRTUAL_ACCOUNT_ID, V3xOrgEntity.ORGENT_TYPE_TEAM));
//        		mav.addObject("startSecondPosts", mem.getSecond_post());
//            }
//        	
//        	templateFlag = true;
//        }
//    	//分支 结束
//        //文单打印权限的控制 -------------
//        /**关于openFrom：从公文档案库传递过来的时候值为edocDocLib,普通文档库（包括共享）为docLib,借阅的时候为lenPotent
//         * 从文档相关消息框弹出来的时候为"null"，暂时只发现这几个值，但是每种情况都会传递参数lenPotent，所以这里判断文单打印权限的时候使用lenPotent来判断*/
//        String printEdocTable="";
//        if("true".equals(request.getParameter("isLibOwner"))){  //文档库相关
//        	printEdocTable="true";
//        }else if(Strings.isNotBlank(lenPotents)){
//        	printEdocTable = "0".equals(lenPotentPrint) ? "false" : "true";
//        }else if("glwd".equals(openFrom)){//从关联文档点击进来的，都不可以打印
//        	printEdocTable="false";
//        }else if("sended".equals(from) || "WaitSend".equals(from)) { //已发送和保存待发
//        	printEdocTable="true";
//        }else if(isSupervisor){//督办节点都能打印
//        	printEdocTable = "true";
//        }else {
//        	printEdocTable = affairCanPrint ? "true" : "false";
//        }
//        mav.addObject("printEdocTable", printEdocTable);
//        //-----
//    	
//        mav.addObject("affairId",_affairId)  ;
//    	mav.addObject("templateFlag", templateFlag);
//    	mav.addObject("from", request.getParameter("from"));
//    	return mav;
//    }
    public ModelAndView wendanTaohong(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	ModelAndView mv = new ModelAndView("edoc/wendantaohong");
    	String s_summaryId = request.getParameter("summaryId");
        long summaryId = Long.parseLong(s_summaryId);
        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
        mv.addObject("summary", summary);
        mv.addObject("body", summary.getFirstBody());
        String tempContentType = request.getParameter("tempContentType");    	
        mv.addObject("tempContentType", tempContentType);
    	return mv;
    }
    public ModelAndView wendanTaohongIframe(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	ModelAndView mv = new ModelAndView("edoc/wendantaohongIframe");  
    	String s_summaryId = request.getParameter("summaryId");    	
        mv.addObject("summaryId", s_summaryId);
        String tempContentType = request.getParameter("tempContentType");    	
        mv.addObject("tempContentType", tempContentType);
    	return mv;
    }
    public ModelAndView getContent2(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView("edoc/edocTopic");
    	String s_summaryId = request.getParameter("summaryId");
        long summaryId = Long.parseLong(s_summaryId);
        
        Affair affair = affairManager.getCollaborationSenderAffair(summaryId);
        //SECURITY 访问安全检查
    	if(!SecurityCheck.isLicit(request, response, ApplicationCategoryEnum.edoc, CurrentUser.get(), summaryId, affair, null)){
    		return null;
    	}
    	
    	String openFrom=request.getParameter("openFrom");
    	String lenPotents=request.getParameter("lenPotent");
        String lenPotent="0";
        if(lenPotents!=null && !"".equals(lenPotents)){lenPotent=lenPotents.substring(0,1);}
        
        String officecanPrint="true";
        String officecanSaveLocal="true";
        String onlySeeContent="false";
        
        if(lenPotents!=null && !"".equals(lenPotents)){officecanSaveLocal="0".equals(lenPotents.substring(1,2))?"false":"true";}
        if(lenPotents!=null && !"".equals(lenPotents)){officecanPrint="0".equals(lenPotents.substring(2,3))?"false":"true";}
        
        if(Byte.toString(com.seeyon.v3x.doc.util.Constants.LENPOTENT_CONTENT).equals(lenPotent))
        {
        	onlySeeContent="true";        	
        }
        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
        modelAndView.addObject("summary", summary);

        modelAndView.addObject("body", summary.getFirstBody());
        
        EdocFormModel fm=new EdocFormModel();
        fm.setEdocSummary(summary);
        fm.setEdocFormId(summary.getFormId());
        fm.setEdocBody(summary.getFirstBody());
        modelAndView.addObject("formModel",fm);
        
        modelAndView.addObject("controller", "edocController.do");        
        modelAndView.addObject("contentRecordId", summary.getEdocBodiesJs());
        
        //记录操作日志
        Long docResId=Long.parseLong(request.getParameter("docId"));
       /**
        operationlogManager.insertOplog(docResId, summaryId,
				ApplicationCategoryEnum.doc, ActionType.LOG_DOC_VIEW, ActionType.LOG_DOC_VIEW+".desc",
				CurrentUser.get().getName(), summary.getSubject());
        **/
        if("glwd".equals(openFrom))//从关联文档点击进来的，都不可以打印
        {
        	officecanPrint="false";
        }
        
        modelAndView.addObject("docId",docResId);
        modelAndView.addObject("officecanPrint",officecanPrint);        	
    	modelAndView.addObject("officecanSaveLocal",officecanSaveLocal);
    	modelAndView.addObject("onlySeeContent",onlySeeContent);
    	modelAndView.addObject("openFrom",openFrom);    	
    	
    	return modelAndView;    	
    }
    

    /**
     * 显示公文内容和处理信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView getContent(HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView(
                "edoc/edocTopic");
        
        String openFrom=request.getParameter("openFrom");
        String lenPotents=request.getParameter("lenPotent");
        String lenPotent="0";
        if(lenPotents!=null && !"".equals(lenPotents)){lenPotent=lenPotents.substring(0,1);}
        String officecanPrint="true";
        String officecanSaveLocal="true";
        
        boolean onlySeeContent=false;
        
        if("lenPotent".equals(openFrom) && Byte.toString(com.seeyon.v3x.doc.util.Constants.LENPOTENT_CONTENT).equals(lenPotent))
        {
        	onlySeeContent=true;
        	return getContent2(request,response);
        }

        String s_summaryId = request.getParameter("summaryId");
        long summaryId = Long.parseLong(s_summaryId);

        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, true);
        modelAndView.addObject("summary", summary);

        modelAndView.addObject("body", summary.getFirstBody());
        
        User user=CurrentUser.get();
        String openFromAffair="";
        
        long userId = user.getId();
        //根据affairId得到权限的处理ID
        long permId=-1;        
        String _affairId = request.getParameter("affairId");
        Affair affair = null;
        String nodePermissionPolicy ="";
        if(Strings.isNotBlank(_affairId))
        {
        	Long affairId = null;
        	try {
        		affairId = new Long(_affairId);
        	} catch (Exception ex) {
        		log.error(ex);
        	}
        	affair=affairManager.getById(affairId);        	
        	if(affair.getState()==StateEnum.col_waitSend.getKey() || affair.getState()==StateEnum.col_sent.getKey())
        	{
        		openFromAffair="waitsendOrSended";
        	}
        	
        	nodePermissionPolicy = edocManager.getPolicyByAffair(affair);
        	String catType= EdocUtil.getEdocMetadataNameEnum(summary.getEdocType()).name();        	
        	//flash bug add adjust field
        	if("collaboration".equalsIgnoreCase(nodePermissionPolicy))
        	{
        		nodePermissionPolicy="niwen";
        		if(summary.getEdocType()==EdocEnum.edocType.recEdoc.ordinal()){nodePermissionPolicy="dengji";}
        	}
        	try{
        		Long accountId=summary.getOrgAccountId();
        		FlowPerm fp=flowPermManager.getFlowPerm(catType,nodePermissionPolicy, accountId);
        		permId=fp.getFlowPermId();
        		String baseAction=fp.getBasicOperation();
        		if(baseAction.indexOf("PrintContentAcc")<0){officecanPrint="false";}
        		if(baseAction.indexOf("SaveContentAcc")<0){officecanSaveLocal="false";}
        	}catch(Exception e){
        		log.error(e);
        	}
        
			if("Pending".equals(request.getParameter("from")))
			{
        		EdocOpinion tempOpinion=edocManager.findBySummaryIdAndAffairId(summaryId, affairId);
        		modelAndView.addObject("tempOpinion", tempOpinion);
        		if(tempOpinion!=null)
        		{
        			modelAndView.addObject("attachments", attachmentManager.getByReference(summaryId,tempOpinion.getId()));
        		}
			}
        }
        if(affair == null){
        	affair = affairManager.getCollaborationSenderAffair(summaryId);
        }
        /* puyc修改   发文关联收文，发文流程上面的所有人都可以看到关联收文*/
		String sendSummaryId = request.getParameter("sendSummaryId");
		boolean showType = false;
		if(Strings.isNotBlank(sendSummaryId)){//从关联文点击进来的
			//发文关联收文，在发文流程上的人有权限看收文
			List<Affair> affairs = affairManager.queryALLAvailabilityAffairList(Long.parseLong(sendSummaryId));
			for(int i=0;i<affairs.size();i++){
    			if(user.getId() == affairs.get(i).getMemberId()){
    				showType = true;
    			}
    		}
		}
		if(!showType){
        //SECURITY 访问安全检查
    	   if(!SecurityCheck.isLicit(request, response, ApplicationCategoryEnum.edoc, user, summaryId, affair, null)){
    		   return null;
    	   }
		}
		/* puyc修改 完毕 */
    	//自动获取签发日期， 封发日期
        if("fengfa".equals(nodePermissionPolicy) && summary.getPackTime()==null){
        	summary.setPackTime(new java.sql.Timestamp(System.currentTimeMillis()));
        }
        if("qianfa".equals(nodePermissionPolicy) && summary.getSigningDate() == null){
        	summary.setSigningDate(new java.sql.Date(System.currentTimeMillis()));
        }

        modelAndView.addObject("affairId", _affairId) ;
        EdocFormModel fm=edocFormManager.getEdocFormModel(summary.getFormId(),summary,permId);
        fm.setEdocBody(summary.getFirstBody());
        modelAndView.addObject("formModel",fm);
        //程炯 太原市政府项目 2012-7-20 begin
        String opinionType = request.getParameter("opinionType");
        //end
        //公文处理意见回显到公文单,排序    
        long flowPermAccout = EdocHelper.getFlowPermAccountId(user.getLoginAccount(), summary, templeteManager);
        //查找公文单节点权限和意见元素绑定
        Hashtable<String, String> locHs = edocFormManager.getOpinionLocation(summary.getFormId(),flowPermAccout);
        //查找公文单意见元素显示。
		EdocOpinionDisplayConfig displayConfig = edocFormManager.getEdocOpinionDisplayConfig(summary.getFormId(),flowPermAccout);
		//程炯 太原市政府项目 2012-7-20 begin
		if(!("".equals(opinionType))&&null!=opinionType&&"2".equals(opinionType)){
			displayConfig.setShowDeptName(true);
		}
		//end
		//lijl添加,将显示类型传入到Dao中-----------------------------------------------Start
		String optionType=request.getParameter("optionType");//意见显示设置的值
		//程炯 太原市政府项目 2012-7-20 begin
		Map<String,EdocOpinionModel> map = edocManager.getEdocOpinion(summary,displayConfig.isOnlyShowLastOpinion(),optionType,opinionType,fm.getEdocFormId());
		//end
		//Map<String,EdocOpinionModel> map = edocManager.getEdocOpinion(summary,displayConfig.isOnlyShowLastOpinion(),optionType);
		//lijl添加,将显示类型传入到Dao中-----------------------------------------------End
		//lijl注销--------------------------------------------------------------------Start
		//Map<String,EdocOpinionModel> map = edocManager.getEdocOpinion(summary,displayConfig.isOnlyShowLastOpinion());
		//lijl注销--------------------------------------------------------------------End
        Map strMap=EdocOpinionDisplayUtil.convertOpinionToString(map,displayConfig,metadataManager,orgManager);

        String opinionsJs = EdocOpinionDisplayUtil.optionToJs(strMap);
      
        modelAndView.addObject("opinionsJs",opinionsJs);
        //发起人意见
        modelAndView.addObject("senderOpinion",strMap.get("senderOpinionList"));
        modelAndView.addObject("senderOpinionAttStr",strMap.get("senderOpinionAttStr"));
        //公文单手写批注回显
        boolean isSender=(user.getId()==summary.getStartUserId());
        modelAndView.addObject("isSender",isSender);
        Long account = EdocHelper.getFlowPermAccountId(user.getLoginAccount(), summary, templeteManager);
        List<String>ols=edocFormManager.getOpinionElementLocationNames(summary.getFormId(),account);
        String hwjs=htmlHandWriteManager.getHandWritesJs(summaryId, user.getName(),ols);
        //if(onlySeeContent){hwjs="<Script language='JavaScript'>hwObjs=new Array();</Script>";}
        modelAndView.addObject("hwjs",hwjs);
        
        modelAndView.addObject("controller", "edocController.do");
        
        modelAndView.addObject("contentRecordId", summary.getEdocBodiesJs());

        //判断是否是部门归档
        String _docId = request.getParameter("docId");
        Long docResId = null;
        boolean isDeptPigeonhole = false;  
        if(Strings.isNotBlank(_docId)){
        	 docResId=Long.parseLong(_docId);
        	 DocResource doc = docHierarchyManager.getDocResourceById(docResId);
        	 if(doc == null) {
        		 super.printV3XJS(response.getWriter());
        		 super.rendJavaScript(response, "alert(getA8Top().dialogArguments.v3x.getMessage('DocLang.doc_alert_source_deleted_doc'));" +
        				 						"getA8Top().window.returnValue = true;" + 
					   					        "getA8Top().window.close();");
				 return null;
        	 }
        	 
        	 if(new Integer(1).equals(doc.getPigeonholeType())){
        		 isDeptPigeonhole=true;
        	 }
        }
        modelAndView.addObject("isDeptPigeonhole", isDeptPigeonhole);
        
		//公文可以移动以后需要兼容其他的情况
		if (Strings.isNotBlank(lenPotents)) {
			officecanPrint = "false";
			officecanSaveLocal = "false";

			officecanSaveLocal = "0".equals(lenPotents.substring(1, 2)) ? "false" : "true";
			officecanPrint = "0".equals(lenPotents.substring(2, 3)) ? "false" : "true";

			modelAndView.addObject("docId", docResId);
		} else if ("glwd".equals(openFrom)) {//从关联文档点击进来的，都不可以打印
			officecanPrint = "false";
		} else if ("waitsendOrSended".equals(openFromAffair)) {
			officecanPrint = "true";
			officecanSaveLocal = "true";
		}
        
        boolean isUnit=false;//是否是联合发文
        if(null!=summary){
        	int edocType = summary.getEdocType();
        	String category = "";
        	if(edocType == EdocEnum.edocType.sendEdoc.ordinal()){
        		category = "edoc_send_permission_policy";
        	}else if(edocType == EdocEnum.edocType.recEdoc.ordinal()){
        		category = "edoc_rec_permission_policy";
        	}else if(edocType == EdocEnum.edocType.signReport.ordinal()){
        		category = "edoc_qianbao_permission_policy";
        	}
        	String opins = this.getOpinionName(category, user.getAccountId());
            modelAndView.addObject("opn", opins);   
            isUnit=summary.getIsunit();
        } 
        
        /********** puyc*************/
		//关联收文
		String relRecs = request.getParameter("relRecs");
	    Long recEdocId = -1L;
	    String relationUrl="";
		if("haveMany".equals(relRecs)){
			 EdocSummaryRelation edocSummaryRelationR = this.edocSummaryRelationManager.findRecEdoc(summaryId, 0);
			 if(edocSummaryRelationR != null){
		        	recEdocId = edocSummaryRelationR.getRelationEdocId();//收文Id
		        	relationUrl = this.relationReceive(recEdocId+"", "1");//收文
		            modelAndView.addObject("relationUrl",relationUrl);//收文的url
		            modelAndView.addObject("relRecs",relRecs);
		       }
		 }
		/********** puyc***end**********/
        
        modelAndView.addObject("officecanPrint",officecanPrint);        	
    	modelAndView.addObject("officecanSaveLocal",officecanSaveLocal);   
    	modelAndView.addObject("openFrom",openFrom);
    	modelAndView.addObject("personInput", EdocSwitchHelper.canInputEdocWordNum());
    	modelAndView.addObject("canTransformToPdf",true);
    	modelAndView.addObject("isBoundSerialNo",edocMarkDefinitionManager.getEdocMarkByTempleteId(summary.getTempleteId(), MarkCategory.serialNo)==null?false:true);
    	
    	String logoURL = EdocHelper.getLogoURL(summary.getOrgAccountId());
        modelAndView.addObject("logoURL", logoURL);
    	return modelAndView;   
    }  

    /**
     * 知会
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView addInform(HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String sSummaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");
        long summaryId = Long.parseLong(sSummaryId);
        long affairId = Long.parseLong(_affairId);
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.inform,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	
	        Affair affair = affairManager.getById(Long.parseLong(_affairId));
	        PrintWriter out = null;
	        if(affair.getState() != StateEnum.col_pending.key()){
	        	out = response.getWriter();
	        	super.printV3XJS(out);
				String msg=ColHelper.getErrorMsgByAffair(affair);
				out.println("<script>");
	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  getA8Top().reFlesh();");
	        	out.println("}");
	        	out.println("</script>");
	        	out.close();
	        	return null;
	        }
	        
	        //从request对象取到选人信息
	        FlowData flowData = FlowData.flowdataFromRequest();
	        //edocManager.addInform(summaryId, affairId, flowData);
	
	        edocManager.addInform(summaryId, affairId, flowData, user.getId()+"");
	        
	        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
	        String caseLogXML = null;
	        String caseProcessXML = null;
	        String caseWorkItemLogXML = null;
	        if (summary != null){
	            if (summary.getCaseId() != null) {
	                Long caseId = summary.getCaseId();
	                caseLogXML = edocManager.getCaseLogXML(caseId);
	                caseProcessXML = edocManager.getModifyingProcessXML(summary.getProcessId());
	                caseWorkItemLogXML = edocManager.getCaseWorkItemLogXML(caseId);
	            }
	            else if (summary.getProcessId() != null && !"".equals(summary.getProcessId())) {
	                String processId = summary.getProcessId();
	                caseProcessXML = edocManager.getProcessXML(processId);
	            }
	        }
	        
	        caseProcessXML = Strings.escapeJavascript(caseProcessXML);
	        caseLogXML = Strings.escapeJavascript(caseLogXML);
	        caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
	
	        String process_desc_by = FlowData.DESC_BY_XML;
	        out = response.getWriter();
	        out.println("<script>");
	        out.println("parent.caseProcessXML = \"" + caseProcessXML + "\";");
	        out.println("parent.caseLogXML = \"" + caseLogXML + "\";");
	        out.println("parent.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
	        out.println("parent.document.all.process_desc_by.value = \"" + process_desc_by + "\";");
	        out.println("parent.document.all.process_xml.value = \"" + caseProcessXML + "\";");
	        out.println("parent.selectInsertPeopleOK();");
	        out.println("</script>");
	        
	        out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;
        //ModelAndView mv= super.redirectModelAndView("/edocController.do?method=showDiagram&summaryId=" + sSummaryId + "&affairId=" + _affairId + "&from=Pending&preAction=addInform");
        //return mv;
    }
    /**
     * 传阅
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView addPassRead(HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String sSummaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");

        long summaryId = Long.parseLong(sSummaryId);
        long affairId = Long.parseLong(_affairId);
        //从request对象取到选人信息
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.inform,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	
	        Affair affair = affairManager.getById(Long.parseLong(_affairId));
	        PrintWriter out = null;
	        if(affair.getState() != StateEnum.col_pending.key()){
	        	out = response.getWriter();
				String msg=ColHelper.getErrorMsgByAffair(affair);
				out.println("<script>");
	        	out.println("alert(\"" + Strings.escapeJavascript(msg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  top.reFlesh();");
	        	out.println("}");
	        	out.println("</script>");
	        	out.close();
	        	return null;
	        }
	        
	        FlowData flowData = FlowData.flowdataFromRequest();
	        edocManager.addPassRead(summaryId, affairId, flowData);
	
	        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
	        String caseLogXML = null;
	        String caseProcessXML = null;
	        String caseWorkItemLogXML = null;
	        if (summary != null){
	            if (summary.getCaseId() != null) {
	                long caseId = summary.getCaseId();
	                caseLogXML = edocManager.getCaseLogXML(caseId);
	                caseProcessXML = edocManager.getModifyingProcessXML(summary.getProcessId());
	                caseWorkItemLogXML = edocManager.getCaseWorkItemLogXML(caseId);
	            }
	            else if (summary.getProcessId() != null && !"".equals(summary.getProcessId())) {
	                String processId = summary.getProcessId();
	                caseProcessXML = edocManager.getProcessXML(processId);
	            }
	        }
	        
	        caseProcessXML = Strings.escapeJavascript(caseProcessXML);
	        caseLogXML = Strings.escapeJavascript(caseLogXML);
	        caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
	
	        String process_desc_by = FlowData.DESC_BY_XML;
	        out = response.getWriter();
	        out.println("<script>");
	        out.println("parent.caseProcessXML = \"" + caseProcessXML + "\";");
	        out.println("parent.caseLogXML = \"" + caseLogXML + "\";");
	        out.println("parent.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
	        out.println("parent.document.all.process_desc_by.value = \"" + process_desc_by + "\";");
	        out.println("parent.document.all.process_xml.value = \"" + caseProcessXML + "\";");
	        out.println("parent.selectInsertPeopleOK();");
	        out.println("</script>");
	        
	        out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
	    return null;
    }
    
//    //加签
//    @Deprecated 
//    public ModelAndView insertPeople(HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//    	User user = CurrentUser.get();
//		String processMode = request.getParameter("processMode");
//		String _summaryId = request.getParameter("summaryId");
//		String _affairId = request.getParameter("affairId");
//		Long summaryId = Long.parseLong(_summaryId);
//		Long affairId = Long.parseLong(_affairId);
//		String policyId = request.getParameter("policyId");
//		String processId = request.getParameter("processId");
//		String policyName = request.getParameter("policyName");
//		
//		
//		String fCategoryName = "";
//		EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
//		if(null!=summary){
//			if(summary.getEdocType() == com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_SEND){
//				fCategoryName = "edoc_send_permission_policy";
//			}else if(summary.getEdocType() == com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_REC){
//				fCategoryName = "edoc_rec_permission_policy";
//			}else if(summary.getEdocType() == com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_SIGN){
//				fCategoryName = "edoc_qianbao_permission_policy";
//			}
//			if(!Strings.isBlank(fCategoryName)){
////				引用节点权限判断，如果是自由流程取发起人所在单位的节点权限，模板取模板所在单位节点权限
//				Long flowPermAccountId = user.getLoginAccount();
//				if(summary.getTempleteId() != null){
//					Templete templete = templeteManager.get(summary.getTempleteId());
//					if(templete != null){
//						flowPermAccountId = templete.getOrgAccountId();
//					}
//				}
//				else{
//					if(summary.getOrgAccountId() != null){
//						flowPermAccountId = summary.getOrgAccountId();
//					}
//				}
////			引用节点权限判断
//	        FlowPermManager flowPermManager=(FlowPermManager)ApplicationContextHolder.getBean("flowPermManager");		
//	        FlowPerm perm = flowPermManager.getFlowPerm(fCategoryName, policyId, flowPermAccountId);
//	        if(perm == null){
//	        	PrintWriter out = response.getWriter();
//				String msg = Constant.getString4CurrentUser("nodePolicy.not.existence");
//				out.println("<script>");
//	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
//	        	out.println("if(window.dialogArguments){"); //弹出
//	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
//	        	out.println("  window.close();");
//	        	out.println("}else{");
//	        	out.println("  parent.getA8Top().reFlesh();");
//	        	out.println("}");
//	        	out.println("</script>");
//	        	out.close();
//	        	return null;
//	        }else{
//	        	try {
//	        		flowPermManager.refFlowPerm(perm.getFlowPermId(), Long.parseLong(user.getLoginAccount()+""), 1);
//				} catch (Exception e) {
//					log.error("", e);
//				}
//	        }	
//			}
//			
//		}
//		
//	
//		boolean isRelieveLock = true;
//		try{
//			//检查同步锁
//	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.insertPeople,
//	        		response, ApplicationCategoryEnum.edoc)){
//	        	isRelieveLock = false;
//	        	return null;
//	        }
//			
//			PrintWriter out = response.getWriter();
//			
//			Affair affair = affairManager.getById(affairId);
//			if(affair.getState() != StateEnum.col_pending.key()){
//				String msg=ColHelper.getErrorMsgByAffair(affair);
//				super.printV3XJS(out);
//				out.println("<script>");
//				out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
//				out.println("if(window.dialogArguments){"); //弹出
//				out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
//				out.println("  window.close();");
//				out.println("}else{");
//				out.println("  getA8Top().reFlesh();");
//				out.println("}");
//				out.println("</script>");
//				out.close();
//				return null;
//			}
//			
//			//保存选人界面返回的信�xi息
//			FlowData flowData = FlowData.flowdataFromRequest();
//			
//	        String node_process_mode = "";
//	        if(flowData.getSeeyonPolicy() != null ){
//	        	node_process_mode = flowData.getSeeyonPolicy().getProcessMode() ;
//	        }
//	        
//			BPMSeeyonPolicy seeyonPolicy = new BPMSeeyonPolicy(policyId, policyName);
//	        if(Strings.isNotBlank(node_process_mode))
//        		seeyonPolicy.setProcessMode(node_process_mode) ;		
//			flowData.setSeeyonPolicy(seeyonPolicy);
//			
//			int iFlowType = 0;
//	        switch(Integer.parseInt(processMode)){
//	            case 0 : iFlowType = FlowData.FLOWTYPE_SERIAL;
//	            break;
//	            case 1 : iFlowType = FlowData.FLOWTYPE_PARALLEL;
//	            break;
//	            case 2 : iFlowType = FlowData.FLOWTYPE_MULTIPLE;
//	            break;
//	            case 3 : iFlowType = FlowData.FLOWTYPE_COLASSIGN;
//	            break;
//	            case 4 : iFlowType = FlowData.FLOWTYPE_NEXTPARALLEL;
//	            break;
//	        }
//			flowData.setType(iFlowType);
//			
//			if (flowData.getPeople().isEmpty()) {
//				throw new RuntimeException("should select one person at least");
//			}
//			
//			//判断当前节点下一节点的节点类型
//	        WorkItemManager wim = null;
//	    	BPMProcess process = null;
//	        try {
//	        	process = ColHelper.getModifyingProcess(processId, user.getId()+"");
//	        	if(process == null)
//	        		process = BPMProcess.fromXML(ColHelper.getRunningProcessByCaseId(summary.getCaseId()).toXML());
//	        	
//	        	if(iFlowType == FlowData.FLOWTYPE_NEXTPARALLEL){
//		    		wim = ColHelper.getWorkitemManager();
//		    		WorkItem workitem = wim.getWorkItemInfo(user.getId() + "", affair.getSubObjectId());
//		    		BPMActivity currentActivity = process.getActivityById(workitem.getActivityId());
//		    		List downTransitions = currentActivity.getDownTransitions();
//		    		BPMTransition nextTran = (BPMTransition) downTransitions.get(0);
//		    		BPMAbstractNode childNode = nextTran.getTo();
//		    		BPMAbstractNode.NodeType nodeType = childNode.getNodeType();
//		    		if(nodeType == BPMAbstractNode.NodeType.end ||
//							nodeType == BPMAbstractNode.NodeType.join){
//		    			String info = Constant.getString4CurrentUser("nextNode.is.specialNode");
//			        	out.println("<script>");
//			        	out.print("alert(\"" + StringEscapeUtils.escapeJavaScript(info) + "\");\n ");
//			        	out.print("parent.enAbleButton();");
//			        	out.println("</script>");
//			        	out.close();
//						return null;
//		    		}
//	        	}
//	    	}catch(ColException e){
//	    		log.error("", e);
//	    	}
//			edocManager.insertPeople(summary, affair, flowData, process, user.getId()+"","insertPeople");
//			
//			String caseLogXML = null;
//			String caseProcessXML = null;
//			String caseWorkItemLogXML = null;
//			
//			if (summary != null){
//				if (summary.getCaseId() != null) {
//					long caseId = summary.getCaseId();
//					caseLogXML = edocManager.getCaseLogXML(caseId);
//					caseProcessXML = edocManager.getModifyingProcessXML(summary.getProcessId());
//					caseWorkItemLogXML = edocManager.getCaseWorkItemLogXML(caseId);
//				}
//				else if (summary.getProcessId() != null && !"".equals(summary.getProcessId())) {
//					caseProcessXML = edocManager.getProcessXML(processId);
//				}
//			}
//			
//			caseProcessXML = Strings.escapeJavascript(caseProcessXML);
//			caseLogXML = Strings.escapeJavascript(caseLogXML);
//			caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
//			
//			String process_desc_by = FlowData.DESC_BY_XML;
//			out.println("<script>");
//	        out.println("parent.window.dialogArguments.caseProcessXML = \"" + caseProcessXML + "\";");
//	        out.println("parent.window.dialogArguments.caseLogXML = \"" + caseLogXML + "\";");
//	        out.println("parent.window.dialogArguments.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
//	        out.println("parent.window.dialogArguments.document.all.process_desc_by.value = \"" + process_desc_by + "\";");
//	        out.println("parent.window.dialogArguments.document.all.process_xml.value = \"" + caseProcessXML + "\";");
//	        out.println("parent.window.dialogArguments.selectInsertPeopleOK();");
//	        out.println("window.close();");
//	        out.println("</script>");
//			
//			out.close();
//			
//			return null;
//		}catch(Exception e){
//        	log.error("", e);
//        }finally{
//        	if(isRelieveLock)
//        		ColLock.getInstance().removeLock(summaryId);
//        }
//        return null;
//    }
    
//  减签前的人员检查
    public ModelAndView preDeletePeople(HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String _summaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");
        Long summaryId = Long.parseLong(_summaryId);
        Long affairId = Long.parseLong(_affairId);
        String processId = request.getParameter("processId");
        
        ModelAndView mv = new ModelAndView("edoc/decreaseNodes");
        
        Affair affair = affairManager.getById(affairId);
        if(affair.getState() != StateEnum.col_pending.key()){
        	PrintWriter out = response.getWriter();
			String msg=ColHelper.getErrorMsgByAffair(affair);
			super.printV3XJS(out);
			out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  getA8Top().reFlesh();");
        	out.println("}");
        	out.println("</script>");
        	out.close();
        	return null;
        }

        FlowData flowData = edocManager.preDeletePeople(summaryId, affairId, processId, user.getId()+"");

        /*response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String peopleJsStr = FlowData.peopleToJs(flowData);

        out.print(peopleJsStr);        
        return null;
        */
        mv.addObject("summmaryId", summaryId);
        mv.addObject("affairId", affairId);
        mv.addObject("flowData", flowData);
        mv.addObject("processId", processId);
        return mv;
    }
    //多级会签匹配人员
    public ModelAndView preAddMoreSign(HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String selObj = request.getParameter("selObj"); 
        String appName = request.getParameter("appName");
        ModelAndView mv = new ModelAndView("edoc/addPeopleSelect");
        if(selObj != null){
        	List<MoreSignSelectPerson> msps=edocManager.findMoreSignPersons(selObj);        
            mv.addObject("msps",msps);
            
            int flowPermType = 1;
            List<FlowPerm> nodePolicyList = null;	
            String nodeMetadataName="";
            if("sendEdoc".equalsIgnoreCase(appName) || "edocSend".equals(appName)){
    			nodeMetadataName=MetadataNameEnum.edoc_send_permission_policy.name();			
    		}else if("recEdoc".equalsIgnoreCase(appName) || "edocRec".equals(appName)){
    			nodeMetadataName=MetadataNameEnum.edoc_rec_permission_policy.name();			
    		}else if("signReport".equalsIgnoreCase(appName) || "edocSign".equals(appName)){
    			nodeMetadataName=MetadataNameEnum.edoc_qianbao_permission_policy.name();			
    		}
            //取得节点权限所属单位ID，分为两种情况，1.公文发起人所在的单位ID，2.模板所属单位的ID
            String _summaryId=request.getParameter("summary_id");
        	Long summaryId = Long.parseLong(_summaryId);
            EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
            long accountId=EdocHelper.getFlowPermAccountId(summary, user.getLoginAccount(), templeteManager);
            nodePolicyList = flowPermManager.getFlowpermsByStatus(nodeMetadataName, FlowPerm.Node_isActive, false, flowPermType,accountId);
            mv.addObject("nodePolicyList",nodePolicyList);
        }
        return mv;
    }
    //多级会签
    public ModelAndView addMoreSign(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
		String _summaryId = request.getParameter("summaryId");
		String _affairId = request.getParameter("affairId");
		Long summaryId = Long.parseLong(_summaryId);
		Long affairId = Long.parseLong(_affairId);		
		String processId = request.getParameter("processId");		
		
		
		EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
			
		boolean isRelieveLock = true;
		try{
			//检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.insertPeople,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
			
			PrintWriter out = response.getWriter();
			
			Affair affair = affairManager.getById(affairId);
			if(affair.getState() != StateEnum.col_pending.key()){
				String msg=ColHelper.getErrorMsgByAffair(affair);
				super.printV3XJS(out);
				out.println("<script>");
				out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
				out.println("if(window.dialogArguments){"); //弹出
				out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
				out.println("  window.close();");
				out.println("}else{");
				out.println("  getA8Top().reFlesh();");
				out.println("}");
				out.println("</script>");
				out.close();
				return null;
			}
			
			//保存选人界面返回的信息
			FlowData flowData = FlowData.flowdataFromRequest();			
			
			int iFlowType = 0;
			iFlowType = FlowData.FLOWTYPE_PARALLEL;
			flowData.setType(iFlowType);
			
			if (flowData.getPeople().isEmpty()) {
				throw new RuntimeException("should select one person at least");
			}
			
			//判断当前节点下一节点的节点类型
	        WorkItemManager wim = null;
	    	BPMProcess process = null;
	        try {
	        	process = ColHelper.getModifyingProcess(processId, user.getId()+"");
	        	if(process == null)
	        		process = BPMProcess.fromXML(ColHelper.getRunningProcessByCaseId(summary.getCaseId()).toXML());
	        		        	
	    	}catch(ColException e){
	    		log.error("", e);
	    	}
	    	
	    	//先增加自己
	    	String curPolicyId=request.getParameter("curPolicyId");
	    	String fCategoryName="";
	    	String curPolicyName="";
	    	FlowPerm perm;
	    	if(summary.getEdocType() == com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_SEND){
					fCategoryName = "edoc_send_permission_policy";
			}else if(summary.getEdocType() == com.seeyon.v3x.edoc.util.Constants.EDOC_FORM_TYPE_REC){
					fCategoryName = "edoc_rec_permission_policy";
			}else{
					fCategoryName = "edoc_qianbao_permission_policy";
			}
	    	perm = flowPermManager.getFlowPerm(fCategoryName, curPolicyId, EdocHelper.getFlowPermAccountId(user.getLoginAccount(), summary, templeteManager));
			if(perm.getType()==FlowPerm.Node_Type_Custome)
			{
				curPolicyName=perm.getName();
			}
			else
			{				
				curPolicyName=ResourceBundleUtil.getString("com.seeyon.v3x.common.resources.i18n.SeeyonCommonResources",perm.getLabel());
	        }
			BPMSeeyonPolicy seeyonPolicy=new BPMSeeyonPolicy(perm.getName(),curPolicyName);
			FlowData curUserFlowData=FlowData.flowdataCurUserFromRequest(user, seeyonPolicy);
			curUserFlowData.setFromType("moreSignSelf");
			edocManager.insertPeople(summary, affair, curUserFlowData, process, user.getId()+"","addMoreSignSelf");
			
			edocManager.insertPeople(summary, affair, flowData, process, user.getId()+"","addMoreSign");
			
			String caseLogXML = null;
			String caseProcessXML = null;
			String caseWorkItemLogXML = null;
			
			if (summary != null){
				if (summary.getCaseId() != null) {
					long caseId = summary.getCaseId();
					caseLogXML = edocManager.getCaseLogXML(caseId);
					caseProcessXML = edocManager.getModifyingProcessXML(summary.getProcessId());
					caseWorkItemLogXML = edocManager.getCaseWorkItemLogXML(caseId);
				}
				else if (summary.getProcessId() != null && !"".equals(summary.getProcessId())) {
					caseProcessXML = edocManager.getProcessXML(processId);
				}
			}
			
			caseProcessXML = Strings.escapeJavascript(caseProcessXML);
			caseLogXML = Strings.escapeJavascript(caseLogXML);
			caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
			
			String process_desc_by = FlowData.DESC_BY_XML;
			out.println("<script>");
	        out.println("parent.window.dialogArguments.caseProcessXML = \"" + caseProcessXML + "\";");
	        out.println("parent.window.dialogArguments.caseLogXML = \"" + caseLogXML + "\";");
	        out.println("parent.window.dialogArguments.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
	        out.println("parent.window.dialogArguments.document.all.process_desc_by.value = \"" + process_desc_by + "\";");
	        out.println("parent.window.dialogArguments.document.all.process_xml.value = \"" + caseProcessXML + "\";");
	        out.println("parent.window.dialogArguments.selectInsertPeopleOK();");
	        out.println("window.close();");
	        out.println("</script>");		
			out.close();
			
			return null;
		}catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;
    }
    //减签
    public ModelAndView deletePeople(HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String _summaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");
        Long summaryId = Long.parseLong(_summaryId);
        Long affairId = Long.parseLong(_affairId);
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.deletePeople,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        
	        PrintWriter out = response.getWriter();
	        Affair affair = affairManager.getById(affairId);
	        if(affair.getState() != StateEnum.col_pending.key()){
				String msg=ColHelper.getErrorMsgByAffair(affair);
				super.printV3XJS(out);
				out.println("<script>");
	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  getA8Top().reFlesh();");
	        	out.println("}");
	        	out.println("</script>");
	        	out.close();
	        	return null;
	        }
	        //保存选人界面返回的信�xi息
	        FlowData flowData = FlowData.flowdataFromRequest();
	
	        if (flowData.getPeople().isEmpty()) {
	            throw new RuntimeException("should select one person at least");
	        }
	
	        List<Party> people = flowData.getPeople();
	
	        edocManager.deletePeople(summaryId, affairId, people, user.getId()+"");
	        
	        if (flowData.getPeople().isEmpty()) {
	            throw new RuntimeException("should select one person at least");
	        }
	
	        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
	        String caseLogXML = null;
	        String caseProcessXML = null;
	        String caseWorkItemLogXML = null;
	        if (summary != null){
	            if (summary.getCaseId() != null) {
	                long caseId = summary.getCaseId();
	                caseLogXML = edocManager.getCaseLogXML(caseId);
	                caseProcessXML = edocManager.getModifyingProcessXML(summary.getProcessId());
	                caseWorkItemLogXML = edocManager.getCaseWorkItemLogXML(caseId);
	            }
	            else if (summary.getProcessId() != null && !"".equals(summary.getProcessId())) {
	                String processId = summary.getProcessId();
	                caseProcessXML = edocManager.getProcessXML(processId);
	            }
	        }
	        
	        caseProcessXML = Strings.escapeJavascript(caseProcessXML);
	        caseLogXML = Strings.escapeJavascript(caseLogXML);
	        caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
	
	        String process_desc_by = FlowData.DESC_BY_XML;
	        out.println("<script>");
	        out.println("parent.caseProcessXML = \"" + caseProcessXML + "\";");
	        out.println("parent.caseLogXML = \"" + caseLogXML + "\";");
	        out.println("parent.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
	        out.println("parent.document.all.process_desc_by.value = \"" + process_desc_by + "\";");
	        out.println("parent.document.all.process_xml.value = \"" + caseProcessXML + "\";");
	        out.println("parent.selectInsertPeopleOK();");
	        out.println("</script>");
	        
	        out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;
        //return super.redirectModelAndView("/edocController.do?method=showDiagram&summaryId=" + _summaryId + "&affairId=" + _affairId + "&from=Pending&preAction=deletePeople");
    }

    /**
     * 撤消流程，变待发(收文分发取回功能，数据到达待分发)
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView cancelBackEdoc(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	PrintWriter out = response.getWriter(); 
        User user = CurrentUser.get();  
        String[] _summaryIds = new String[]{};
        String repealComment = request.getParameter("repealComment"); //撤销附言 
        _summaryIds = request.getParameterValues("id");
        
        boolean isRelieveLock = true;
        try{
	        int result = 0;
	        StringBuffer info = new StringBuffer();
	        //lijl添加空值判断,如果为空则提示"流程撤销错误!"
	        if(_summaryIds!=null){
	        	if(_summaryIds.length>0){
	        		for (int i = 0; i < _summaryIds.length; i++) {
	        			Long summaryId = Long.parseLong(_summaryIds[i]);
	        			
	        			EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false); 
	        			if(summary.getFinished()){result=1;}

	        			edocManager.edocBackCancelSummary(user.getId(), summaryId, repealComment, "");
	        			
	        			if (result == 1) {
	        				info.append("《").append(summary.getSubject()).append("》");
	        			} else {
	        				try{
	        					updateIndexManager.getIndexManager().deleteFromIndex(EdocUtil.getAppCategoryByEdocType(summary.getEdocType()),summary.getId());
	        				}catch(Exception e){
	        					log.error("撤销公文流程，更新全文检索异常",e);
	        				}
	        				//撤销流程事件
	        				CollaborationCancelEvent event = new CollaborationCancelEvent(this);
	        				event.setSummaryId(summary.getId()); 
	        				event.setUserId(user.getId());
	        				event.setMessage(repealComment);
	        				EventDispatcher.fireEvent(event);
	        			}		           
	        			try{
	        				//解锁正文文单
	        				unLock(user.getId(),summary);
	        			}catch(Exception e){
	        				log.error(e);
	        			}
	        		}
	        	}else{
		        	String alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.back.flow.error");
		        	out.println("<script>");
		        	out.println("<!--");
		        	out.println("alert('"+alertStr+"');");
		        	out.println("//-->");
		        	out.println("</script>");
		        	return null;
		        }
	        }else{
	        	String alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.back.flow.error");
	        	out.println("<script>");
	        	out.println("<!--");
	        	out.println("alert('"+alertStr+"');");
	        	out.println("//-->");
	        	out.println("</script>");
	        	return null;
	        }
	          
	        super.printV3XJS(out); 
	        if(info.length() > 0){   
	        	String alertStr="";
	        	alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.state.end.alert",info.toString());
	        	if(alertStr.indexOf("$")>-1){  
	        		alertStr = alertStr.replace("$", "");
	        	}
	        	
	        	if(result==1) {
		        	out.println("<script>");
		        	out.println("<!--");
		        	out.println("alert(\""+StringEscapeUtils.escapeJavaScript(alertStr)+"\");");
		        	out.println("//-->");
		        	out.println("</script>");
	        	}
	        	return null;
	        }	        
	        out.println("<script>");
	    	out.println("if(window.dialogArguments){"); //弹出
	    	out.println("  window.returnValue = \"true\";");
	    	out.println("  window.close();");
	    	out.println("}else{");
    		out.println("  parent.location.reload(true);");
	    	out.println("}");
	    	out.println("</script>");
	    	return null;
        } catch(Exception e) {
        	log.error("", e);
        } finally {
        	if(isRelieveLock){
        		for(int i=0; i<_summaryIds.length; i++){
        			ColLock.getInstance().removeLock(Long.parseLong(_summaryIds[i]));
        		}
        	}
        }
        return null;
    }
    
    /**
     * 撤消流程，已发变待发(收文分发取回功能，数据到达待分发)
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView repeal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	PrintWriter out = response.getWriter(); 
        User user = CurrentUser.get();  
        String[] _summaryIds = new String[]{};
        String page = request.getParameter("page");
        StringBuffer info = new StringBuffer();
        String repealComment = request.getParameter("repealComment"); //撤销附言 
        //lijl添加,为了区分是撤销流程还是取回

        String docBack = request.getParameter("docBack");//docBack取回/cancelColl撤销 
        //GOV-4082 发文流程撤销确定后没有反应。另发现撤销和退回拟稿人功能重复
        if(Strings.isBlank(docBack)){
        	docBack = "";
        }

        if("workflowManager".equals(page)){
        	String[] summaryIdArr = {request.getParameter("summaryId")};
        	_summaryIds = summaryIdArr;
        } else {
        	_summaryIds = request.getParameterValues("id");
          	if("dealrepeal".equals(page)){
        		repealComment = request.getParameter("content");        		
        	}
        }
        
        boolean isRelieveLock = true;
        try{
	        int result = 0;
	        List<Affair> doneList = null;
	        //lijl添加空值判断,如果为空则提示"流程撤销错误!"
	        if(_summaryIds!=null){
	        	if(_summaryIds.length>0){
	        		for (int i = 0; i < _summaryIds.length; i++) {
	        			Long summaryId = Long.parseLong(_summaryIds[i]);
	        			//检查同步锁
	        			if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.cancel, response, ApplicationCategoryEnum.edoc)){
	        				isRelieveLock = false;
	        				return null;
	        			}
	        			EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false); 
	        			if(summary.getFinished()){result=1;}
	        			//else if(summary.getHasArchive()){result=2;}
	        			else {
	        				Map<String, Object> conditions = new HashMap<String, Object>();
	        				conditions.put("objectId", summary.getId());
	        				conditions.put("app", ApplicationCategoryEnum.edocRec.key());
	        				List<Integer> states = new ArrayList<Integer>();
	        				states.add(StateEnum.col_done.key());
	        				states.add(StateEnum.col_stepStop.key());
	        				conditions.put("state", states);
	        				doneList = affairManager.getByConditions(conditions);
	        				if((doneList != null && doneList.size()>0) && "docBack".equals(docBack)) {//处理中不能取回
	        					result = 3;//已有人员
	        				} else {
	        					//删除收文(暂物理删除) 撤销/取回都要删除分发数据
	        					if(1==summary.getEdocType()){
	        						summary.setState(Constant.flowState.deleted.ordinal());				
	        					}
	        					result = edocManager.cancelSummary(user.getId(), summaryId, repealComment,docBack);
	        					//收文撤销，取回，数据到达待分发。
	        					if(1==summary.getEdocType()) {
	        						//affairManager.deleteByObject(ApplicationCategoryEnum.edocRecDistribute, summary.getId());
	        						Map<String, Object> distributerConditions = new HashMap<String, Object>();
	        						distributerConditions.put("objectId", summary.getId());
	        						distributerConditions.put("app", ApplicationCategoryEnum.edocRecDistribute.key());
	    	        				List<Integer> distributerStates = new ArrayList<Integer>();
	    	        				distributerStates.add(StateEnum.col_done.key());
	    	        				distributerConditions.put("state", distributerStates);
	    	        				List<Affair> distributerDoneList = affairManager.getByConditions(distributerConditions);
	    	        				for(int k=0; k<distributerDoneList.size(); k++) {
	    	        					distributerDoneList.get(k).setState(StateEnum.col_pending.key());
	    	        					affairManager.updateAffair(distributerDoneList.get(k));
	    	        				}
	        						EdocRegister edocRegister = edocRegisterManager.findRegisterByDistributeEdocId(summaryId); 
	        						if(edocRegister!=null) {
	        							edocRegister.setDistributeEdocId(-1);
	        							edocRegister.setDistributeDate(null);
	        							//GOV-3328 （需求检查）【公文管理】-【收文管理】-【分发】，已分发纸质公文撤销后到待分发列表中了，应该在草稿箱中
	        							if("docBack".equals(docBack)){
	        								edocRegister.setDistributeState(EdocNavigationEnum.EdocDistributeState.WaitDistribute.ordinal());//将状态设置为"未分发"
	        							}
	        							
	        							//撤销与取回时，登记对象退回状态为：0
	        							edocRegister.setIsRetreat(0);//非退回
	        							edocRegisterManager.update(edocRegister);
	        						}
	        					}
	        				}
	        			}
	        			if (result == 1 || result == -1 || (result == 3 && "docBack".equals(docBack))) {	                
	        				info.append("《").append(summary.getSubject()).append("》");
	        			} else {
	        				try{
	        					updateIndexManager.getIndexManager().deleteFromIndex(EdocUtil.getAppCategoryByEdocType(summary.getEdocType()),summary.getId());
	        				}catch(Exception e){
	        					log.error("撤销公文流程，更新全文检索异常",e);
	        				}
	        				//撤销流程事件
	        				CollaborationCancelEvent event = new CollaborationCancelEvent(this);
	        				event.setSummaryId(summary.getId()); 
	        				event.setUserId(user.getId());
	        				event.setMessage(repealComment);
	        				EventDispatcher.fireEvent(event);
	        				//发送消息给督办人，更新督办状态，并删除督办日志、删除督办记录、删除催办次数
	        				this.colSuperviseManager.updateStatusAndNoticeSupervisorWithoutMes(summaryId, Constant.superviseType.edoc.ordinal(), Constant.superviseState.waitSupervise.ordinal());	            
	        			}		           
	        			try{
	        				//解锁正文文单
	        				unLock(user.getId(),summary);
	        			}catch(Exception e){
	        				log.error(e);
	        			}
	        		}
	        	}else{
		        	String alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.back.flow.error");
		        	out.println("<script>");
		        	out.println("<!--");
		        	out.println("alert('"+alertStr+"');");
		        	out.println("//-->");
		        	out.println("</script>");
		        	return null;
		        }
	        }else{
	        	String alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.back.flow.error");
	        	out.println("<script>");
	        	out.println("<!--");
	        	out.println("alert('"+alertStr+"');");
	        	out.println("//-->");
	        	out.println("</script>");
	        	return null;
	        }
	        
	          
	        super.printV3XJS(out); 
	        if(info.length() > 0){   
	        	String alertStr="";
	        	if(result == -1) {//撤销
	        		alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.state.system.running", info.toString());
	        	} else  if(result == 3) {//取回
	        		alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.is.running", info.toString());
	        	}
//	        	else if(result == 2)//已归档撤销
//	        	{
//	        		alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.archive.notoperate");
//	        	}
	        	else {
	        		if("docBack".equals(docBack)) {//流程结束，取回提示
	        			alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.back.state.end.alert",info.toString());
	        		} else {
	        			alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.state.end.alert",info.toString());
	        		}
	        	}
	        	//GOV-3412 公文管理-收文管理-分发-已分发中，选择一条正在处理中的公文点击【取回】提示消息不对
	        	//很奇怪，调用ResourceBundleUtil.getString之后，会在提示中加入$, 先暂时这样处理 changyi add
	        	if(alertStr.indexOf("$")>-1){  
	        		alertStr = alertStr.replace("$", "");
	        	}
	        	
	        	if((result == 3 && "docBack".equals(docBack)) || result==1) {
		        	out.println("<script>");
		        	out.println("<!--");
		        	out.println("alert(\""+StringEscapeUtils.escapeJavaScript(alertStr)+"\");");
		        	out.println("//-->");
		        	out.println("</script>");
	        	}
	        	return null;
	        }	        
	        if("workflowManager".equals(page)){
	        	out.println("<script>");
		    	out.println("if(window.dialogArguments){"); //弹出
		    	out.println("  window.returnValue = \"true\";");
		    	out.println("  window.close();");
		    	out.println("}else{");
		    	out.println("  parent.ok();");
		    	out.println("}");
		    	out.println("</script>");
		    	out.close();
		    	return null;
	        }else{
		        out.println("<script>");
		    	out.println("if(window.dialogArguments){"); //弹出
		    	out.println("  window.returnValue = \"true\";");
		    	out.println("  window.close();");
		    	out.println("}else{");
		    	if("dealrepeal".equals(page)) {
		    		//out.println("  parent.parent.parent.location.reload(true);");
		    		
		    		//GOV-2873 【公文管理】-【发文管理】-【待办】，处理待办公文时点击'撤销'报错
		    		String alertStr=ResourceBundleUtil.getString("com.seeyon.v3x.exchange.resources.i18n.ExchangeResource","exchange.receiveRecord.receive.already.label");
		    		out.println("alert('"+alertStr+"');");
		    		out.println("top.close();");
		    		out.println("top.opener.location.href = top.opener.location.href;");
		    	} else {
		    		out.println("  parent.location.reload(true);");
		    	}
		    	out.println("}");
		    	out.println("</script>");
		    	return null;
	        }
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock){
        		for(int i=0; i<_summaryIds.length; i++){
        			ColLock.getInstance().removeLock(Long.parseLong(_summaryIds[i]));
        		}
        	}
        }
        return null;
    }
    
    //回退
    public ModelAndView stepBack(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get(); 
        String _summaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");
        Long summaryId = Long.parseLong(_summaryId);
        Long affairId = Long.parseLong(_affairId);
        String processId = request.getParameter("processId");
        boolean isRelieveLock = true;
        EdocSummary summary = null ;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.stepback,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        
	        Affair _affair = affairManager.getById(affairId);
	        //补上退回时间
//	        _affair.setUpdateDate(DateUtil.getDate(DateUtil.getDate()));
	        PrintWriter out = response.getWriter();
	        String errMsg="";
	        if(_affair.getState() != StateEnum.col_pending.key()){
	        	errMsg=ColHelper.getErrorMsgByAffair(_affair);				
	        }
	        if("".equals(errMsg))
	        {
	        	summary=edocSummaryManager.findById(summaryId);
//	        	if(summary.getHasArchive())
//	        	{
//	        		errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.archive.notoperate");
//	        	}else 
	        	if(summary.getFinished()){
	        		errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.state.end.stepback.alert","《"+summary.getSubject()+"》");
	        	}
	        }
	        if(!"".equals(errMsg))
	        {
	        	out.println("<script>");
	        	out.println("<!--");
	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(errMsg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  parent.parent.location.reload(true);");
	        	out.println("}");
	        	out.println("//-->");
	        	out.println("</script>");
	        	out.close();
	        	return null;	        	
	        }
	
	        //保存回退时的意见,附件�?
	        EdocOpinion signOpinion = new EdocOpinion(); 
	        bind(request, signOpinion);

	        String content = request.getParameter("contentOP");
	        signOpinion.setContent(content);
	        
	        String attitude = request.getParameter("attitude");
	        if(!Strings.isBlank(attitude)){
	        	signOpinion.setAttribute(Integer.valueOf(attitude).intValue());
	        }else{
	        	signOpinion.setAttribute(com.seeyon.v3x.edoc.util.Constants.EDOC_ATTITUDE_NULL);
	        }
	        //回退的时候,选择归档,跟踪无效
	        //String afterSign = request.getParameter("afterSign");
	
	        signOpinion.isDeleteImmediate = false;//"delete".equals(afterSign);
	        signOpinion.affairIsTrack = false;//"track".equals(afterSign);
	
	        signOpinion.setIsHidden(request.getParameterValues("isHidden") != null);
	        signOpinion.setIdIfNew();
	        
	        long nodeId=-1;
	        if(request.getParameter("currentNodeId")!=null && !"".equals(request.getParameter("currentNodeId")))
	        {
	        	nodeId=Long.parseLong(request.getParameter("currentNodeId"));
	        }
	        signOpinion.setNodeId(nodeId);
	        
//	      	//设置代理人信息
	        if(user.getId()!= _affair.getMemberId())
	        {
	        	signOpinion.setProxyName(user.getName());
	        }
	        signOpinion.setCreateUserId(_affair.getMemberId());
	        //保存附件
	        //先删除原有附件，修改bug15597
	        String oldOpinionIdStr=request.getParameter("oldOpinionId");
	        if(!"".equals(oldOpinionIdStr))
	        {
	        	this.attachmentManager.deleteByReference(summaryId, Long.parseLong(oldOpinionIdStr));
	        }
	        //this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, signOpinion.getId(), request);
	        //使用附件组件重构
            AttachmentEditHelper editHelper = new AttachmentEditHelper(request);
            if(editHelper.hasEditAtt()){//是否修改附件
            	edocManager.saveUpdateAttInfo(editHelper.attSize(),summaryId,editHelper.parseProcessLog(Long.parseLong(processId), nodeId));
            }
        	this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, signOpinion.getId(), request);
	
	        //true:成功回退 false:不允许回退
	        boolean ok = edocManager.stepBack(summaryId, affairId,signOpinion);       
	        //TODO 不允许回退提示待完成
	        
	        //lijl添加,在退回时设置Edoc_Option的state的状态为1------------------------State
	        String optionType=request.getParameter("optionType");
	        //1、3都表是只保留最后一条意见
	        if("1".equals(optionType)){
	        	signOpinion.setState(2);
	        	//退回的时候要把以前是0的情况改为2
	        	edocManager.update(summaryId,user.getId(),signOpinion.getPolicy(),2,0);
	        }else if("3".equals(optionType)){
	        	signOpinion.setState(2);
	        	//退回的时候要把以前是0的情况改为2
	        	edocManager.update(summaryId,user.getId(),signOpinion.getPolicy(),2,0);
	        }
	        //lijl添加,在退回时设置Edoc_Option的state的状态为1------------------------End
	        //lijl注销下边的方法,因为在退回的时候会删除该公文的所有日志,所以没有必要再添加日志
//	        //lijl添加,通过流程ID获取刚插入的流程日志对象,并将意见设置到param5中------------------Start
//        	Long processid=0L;
//        	if(summary!=null){
//        		processid=Long.parseLong(summary.getProcessId());
//        	}
//        	ProcessLog processLog=processLogManager.getProcessLogByProcessIdMaxTime(processid);
//        	if(processLog != null) {
//	        	//将意见添加到param5中
//	        	processLog.setParam5(signOpinion.getContent());
//	        	processLogManager.update(processLog);
//        	}
//        	//lijl添加,通过流程ID获取刚插入的流程日志对象,并将意见设置到param5中------------------End
        	
	        //回退成功后，跳到待办列表�?
	        //return super.refreshWorkspace();
	        out.println("<script>");
	    	out.println("parent.closeWindow();");
	    	out.println("</script>");
	    	out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
	           
            try{
            	//解锁正文文单
            	unLock(user.getId(),summary);
            }catch(Exception e){
            	log.error(e);
            }

        }
        
        return super.refreshWorkspace();
    }
    
    /**
     * 会签
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView colAssign(HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String sSummaryId = request.getParameter("summaryId");
        String _affairId = request.getParameter("affairId");

        long summaryId = Long.parseLong(sSummaryId);
        long affairId = Long.parseLong(_affairId);
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.colAssign,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        
	        Affair affair = affairManager.getById(affairId);
	        PrintWriter out = null;
	        if(affair.getState() != StateEnum.col_pending.key()){
	        	out = response.getWriter();
				String msg=ColHelper.getErrorMsgByAffair(affair);
				super.printV3XJS(out);
				out.println("<script>");
	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  getA8Top().reFlesh();");
	        	out.println("}");
	        	out.println("</script>");
	        	out.close();
	        	return null;
	        }
	        //从request对象取到选人信息
	        FlowData flowData = FlowData.flowdataFromRequest();
	
	        edocManager.colAssign(summaryId, affairId, flowData, user.getId()+"");
	        
	        //colManager.colAssign(summaryId, affairId, flowData, user.getId()+"");
	        
	        EdocSummary summary = edocManager.getEdocSummaryById(summaryId, false);
	        String caseLogXML = null;
	        String caseProcessXML = null;
	        String caseWorkItemLogXML = null;
	        if (summary != null){
	            if (summary.getCaseId() != null) {
	                long caseId = summary.getCaseId();
	                caseLogXML = edocManager.getCaseLogXML(caseId);
	                caseProcessXML = edocManager.getModifyingProcessXML(summary.getProcessId());
	                caseWorkItemLogXML = edocManager.getCaseWorkItemLogXML(caseId);
	            }
	            else if (summary.getProcessId() != null && !"".equals(summary.getProcessId())) {
	                String processId = summary.getProcessId();
	                caseProcessXML = edocManager.getProcessXML(processId);
	            }
	        }
	        
	        caseProcessXML = Strings.escapeJavascript(caseProcessXML);
	        caseLogXML = Strings.escapeJavascript(caseLogXML);
	        caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
	
	        String process_desc_by = FlowData.DESC_BY_XML;
	        Boolean isMatch = false;
	        out = response.getWriter();
	        out.println("<script>");
	        if((Boolean)BrowserFlag.PageBreak.getFlag(request)){
		        out.println("parent.window.dialogArguments.caseProcessXML = \"" + caseProcessXML + "\";");
		        out.println("parent.window.dialogArguments.caseLogXML = \"" + caseLogXML + "\";");
		        out.println("parent.window.dialogArguments.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
		        out.println("parent.window.dialogArguments.document.getElementById('process_desc_by').value = \"" + process_desc_by + "\";");
		        out.println("parent.window.dialogArguments.document.getElementById('isMatch').value = \""+isMatch+"\";");
		        out.println("parent.window.dialogArguments.document.getElementById('process_xml').value = \"" + caseProcessXML + "\";");
		        out.println("parent.window.dialogArguments.selectInsertPeopleOK();");
		        out.println("top.close();");
	        }else{
		        out.println("parent.parent.caseProcessXML = \"" + caseProcessXML + "\";");
		        out.println("parent.parent.caseLogXML = \"" + caseLogXML + "\";");
		        out.println("parent.parent.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
		        out.println("parent.parent.document.getElementById('process_desc_by').value = \"" + process_desc_by + "\";");
		        out.println("parent.parent.document.getElementById('isMatch').value = \""+isMatch+"\";");
		        out.println("parent.parent.document.getElementById('process_xml').value = \"" + caseProcessXML + "\";");
		        out.println("parent.parent.selectInsertPeopleOK();");
		        out.println("parent.parent.$('#colAssignWin').dialog('destroy');");
	        }
	        out.println("</script>");
	        
	        out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;

        /*String xmlJavaScript=EdocHelper.getWorkFlowInfoScript(summaryId, edocManager);
        PrintWriter out = response.getWriter();
        out.println(xmlJavaScript);
        out.close();
        return null;*/
        //return super.redirectModelAndView("/edocController.do?method=showDiagram&summaryId=" + sSummaryId + "&affairId=" + _affairId + "&from=Pending&preAction=colAssign");
    }
    
    //取回
    public ModelAndView takeBack(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String[] affairIds = request.getParameterValues("affairId");
        String[] summaryIds = request.getParameterValues("summaryId");
        boolean isRelieveLock = true;
        try{
	        StringBuffer info = new StringBuffer();
	        StringBuffer info1 = new StringBuffer(); 
			StringBuffer info2 = new StringBuffer();
	        if (affairIds != null) {
	        	int i=0;
	            for (String affairId : affairIds) {
	                Long _affairId = new Long(affairId);
	                Long summaryId = Long.parseLong(summaryIds[i]);
	                //检查同步锁
	                if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.tackback,
	                		response, ApplicationCategoryEnum.edoc)){
	                	isRelieveLock = false;
	                	return null;
	                }
	                EdocSummary summary=edocManager.getEdocSummaryById(summaryId,false);
					Affair affair = affairManager.getById(_affairId);
					// if (summary.getFinished()) {
					// info1.append("《").append(summary.getSubject()).append(
					// "》").append("\n");
					// continue;
					// }

//					if (summary.getHasArchive()) {
//						// 公文被归档
//						// 输出提示信息，提示公文不能够被取回
//						info2.append("《").append(summary.getSubject()).append(
//								"》").append("\n");
//						continue;
//					}
					if (isBeSended(summaryId)){
						// 公文被发送
						// 输出提示信息，提示公文不能够被取回
						info1.append("《").append(summary.getSubject()).append(
								"》").append("\n");
						continue;
					}
	                boolean ok = edocManager.takeBack(_affairId);
	                if(ok==false)
	                {
	                	if(affair!=null)
	                	{
	                		info.append("《").append(affair.getSubject()).append("》").append("\n");
	                    }
	                }
	                i++;
	            }
	        }
	        if(info.length() > 0){
	        	WebUtil.saveAlert(ResourceBundleUtil.getString("com.seeyon.v3x.collaboration.resources.i18n.CollaborationResource","takeBack.not.label",info.toString()));
	        }
	        if(info1.length() > 0){
				WebUtil.saveAlert(ResourceBundleUtil.getString(
						"com.seeyon.v3x.edoc.resources.i18n.EdocResource",
						"edoc.state.end.takeback.sendalert", info1.toString()));
	        }
			if (info2.length() > 0) {
				WebUtil.saveAlert(ResourceBundleUtil.getString(
						"com.seeyon.v3x.edoc.resources.i18n.EdocResource",
						"edoc.state.end.takeback.archivealert", info2
								.toString()));
			}
	        return super.refreshWindow("parent");
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock){
        		for(int i=0; i<summaryIds.length; i++){
        			ColLock.getInstance().removeLock(Long.parseLong(summaryIds[i]));
        		}
        	}
        }
        return super.refreshWorkspace();
    }
    /**
     * 删除
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView delete(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
    	
        String[] affairIds = request.getParameterValues("affairId");
        String pageType = request.getParameter("pageType");
        if (affairIds != null) {
            for (String affairId : affairIds) {
                Long _affairId = new Long(affairId);
                Long logAffair = new Long(affairId);
                edocManager.deleteAffair(pageType, _affairId);
                /**puyc 添加日志**/
        		appLogManager.insertLog(CurrentUser.get(), AppLogAction.Edoc_delete, CurrentUser.get().getName(),affairManager.getById(logAffair).getSubject());
            }
        }
        return super.refreshWindow("parent");
        //return super.refreshWorkspace();

//        return super.redirectModelAndView("/collaboration.do?method=" + request.getParameter("from"));
    }
    
    //终止
    public ModelAndView stepStop(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        String _summaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");
        Long summaryId = Long.parseLong(_summaryId);
        Long affairId = Long.parseLong(_affairId);
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.stepstop,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        Affair _affair = affairManager.getById(affairId);
	        //保存终止时的意见,附件�
	        EdocOpinion signOpinion = new EdocOpinion();
	        bind(request, signOpinion);
	        
	        String attitude = request.getParameter("attitude");
	        if(!Strings.isBlank(attitude)){
	        	signOpinion.setAttribute(Integer.valueOf(attitude).intValue());
	        }else{
	        	signOpinion.setAttribute(com.seeyon.v3x.edoc.util.Constants.EDOC_ATTITUDE_NULL);
	        }
	
	        String afterSign = request.getParameter("afterSign");
	
	        signOpinion.isDeleteImmediate = "delete".equals(afterSign);
	        signOpinion.affairIsTrack = "track".equals(afterSign);
	
	        signOpinion.setIsHidden(request.getParameterValues("isHidden") != null);
	        signOpinion.setIdIfNew();
	        
	        long nodeId=-1;
	        if(request.getParameter("currentNodeId")!=null && !"".equals(request.getParameter("currentNodeId")))
	        {
	        	nodeId=Long.parseLong(request.getParameter("currentNodeId"));
	        }
	        signOpinion.setNodeId(nodeId);
//	      	//设置代理人信息
	        if(user.getId()!= _affair.getMemberId())
	        {
	        	signOpinion.setProxyName(user.getName());
	        }
	        signOpinion.setCreateUserId(_affair.getMemberId());
	        
	        //保存附件
	        this.attachmentManager.create(ApplicationCategoryEnum.collaboration, summaryId, signOpinion.getId(), request);
	
	        edocManager.stepStop(summaryId, affairId,signOpinion);  
	        //程炯 太原市政府项目 2012-7-26 流程终止删除请示卡内容
	        if(edocManager.getEdocSummaryById(summaryId, true).getEdocType() == EdocEnum.edocType.signReport.ordinal()){
	        	configManager.deleteConfigItem(SHANG_KA, summaryId+"", user.getAccountId());
	        }
	        
	        //终止成功后，跳到待办列表�?
	        PrintWriter out = response.getWriter();			
			super.printV3XJS(out);
			out.println("<script>");        	
			out.println("parent.closeWindow();");
        	out.println("</script>");
        	out.close();
        	return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;
        //return super.redirectModelAndView("/collaboration.do?method=showDiagram&summaryId=" + _summaryId + "&affairId=" + _affairId + "&from=Pending&preAction=stepBack");
    }
    
    /**
     * 流程管理界面直接终止流程
     * @author jincm 2008-6-05
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView stopflow(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
    	String _summaryId = request.getParameter("summaryId");
        Long summaryId = Long.parseLong(_summaryId);
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.stepstop,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	
	        //保存终止时的意见,附件�
	        EdocOpinion signOpinion = new EdocOpinion();
	        bind(request, signOpinion);
	        
	        String attitude = request.getParameter("attitude");
	        if(!Strings.isBlank(attitude)){
	        	signOpinion.setAttribute(Integer.valueOf(attitude).intValue());
	        }else{
	        	signOpinion.setAttribute(com.seeyon.v3x.edoc.util.Constants.EDOC_ATTITUDE_NULL);
	        }
	        
	        signOpinion.isDeleteImmediate = false;
	        signOpinion.affairIsTrack = false;
	        signOpinion.setIsHidden(false);
	        signOpinion.setIdIfNew();
	
	        edocManager.stepStop(summaryId, null, signOpinion);       
	        //终止成功后，跳到待办列表�
        	PrintWriter out = response.getWriter();			
			super.printV3XJS(out);
	        out.println("<script>");
	    	out.println("if(window.dialogArguments){"); //弹出
	    	out.println("  window.returnValue = \"true\";");
	    	out.println("  window.close();");
	    	out.println("}else{");
	    	out.println("  parent.ok();");
	    	out.println("}");
	    	out.println("</script>");
	    	out.close();
	    	return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;
    }

    //公文已发，已办归档
    public ModelAndView pigeonhole(HttpServletRequest request,HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView("edoc/listDone");
    	String[] affairIds = request.getParameterValues("affairId");
        String pageType = request.getParameter("pageType");
        String edocType = request.getParameter("edocType");
        String _archiveId = request.getParameter("archiveId"); 

    	
        Long archiveId=null;
        if(Strings.isNotBlank(_archiveId)){
        	archiveId=Long.parseLong(_archiveId);
        }
        
        StringBuffer sbInfo=new StringBuffer();
        StringBuffer accInfo=new StringBuffer();
        String nodePermissionPolicy;
        MetadataNameEnum edocTypeEnum;
     //   User user = CurrentUser.get();
        String needChoosePigeonholeSubject= "";//需要选择归档归档的公文。
        String needChoosePigeonholeIds="";
        int successCount=0;
        Set filterSet=new HashSet();
        if (affairIds != null) {
            for (String affairId : affairIds) {
            	if(Strings.isBlank(affairId)) continue;
            	if(filterSet.contains(affairId))
            		continue;
            	else 
            		filterSet.add(affairId);
            	
                Long _affairId = new Long(affairId);
                Affair affair=affairManager.getById(_affairId);
                EdocSummary summary=edocManager.getEdocSummaryById(affair.getObjectId(), false);
                if(archiveId != null)summary.setArchiveId(archiveId);
                boolean docResourceExist = docHierarchyManager.docResourceExist(summary.getArchiveId());
                if(summary.getArchiveId() == null || !docResourceExist) {
                	needChoosePigeonholeSubject+="《"+affair.getSubject()+"》<br>";
                	needChoosePigeonholeIds +=affair.getId()+",";
                }
                
                edocTypeEnum=EdocUtil.getEdocMetadataNameEnumByApp(affair.getApp());
                try
                {
                	nodePermissionPolicy = edocManager.getPolicyByAffair(affair);
                	if("finish".equals(pageType))
                	{//已办事项，归档判断处理时，是否有归档权限
                		
                		List<String> baseActions = permissionManager.getActionList(edocTypeEnum.name(), nodePermissionPolicy, "basic", summary.getOrgAccountId());
                		if(baseActions.contains("Archive")==false)
                		{
                			if(accInfo.length()>0){accInfo.append(",");}
                			accInfo.append(affair.getSubject());
                			continue;
                		}
                	}
                	
                	//是否有没有设置预归档路径的公文
                	if(summary.getArchiveId()!=null && docResourceExist){
                		affair.setNodePolicy(nodePermissionPolicy);
                		edocManager.pigeonholeAffair(pageType, _affairId, affair.getObjectId(),archiveId);
                		successCount++; //统计归档成功的个数。
                	}
                }catch(EdocException e)
                {
                	if(e.getErrNum()==EdocException.errNumEnum.workflow_not_finish.ordinal())
                	{
                		if(sbInfo.length()>0){sbInfo.append(",");}
                		sbInfo.append(e.getMessage());
                	}
                	else
                	{
                		throw e;
                	}
                }
            }
        }
   
        
        PrintWriter out = response.getWriter();
        if(!"".equals(needChoosePigeonholeSubject)){//假设有需要选择归档路径的公文
        	String confirmInfo="";
        	if(successCount != 0){
        		confirmInfo= ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.pigdoc.alert.list",successCount,needChoosePigeonholeSubject);
        	}else{//没有成功归档的。
        		confirmInfo = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.pigdoc.alert.list.needchoose",needChoosePigeonholeSubject);
        	}
		    String js="if(confirm('"+confirmInfo.replace("<br>", "\\r\\n")+"')){\r\n"+
    		"var selectIds = '"+needChoosePigeonholeIds.substring(0,needChoosePigeonholeIds.length()-1)+"';\r\n"+
    		"var ids=document.getElementsByName('id');for(var i=0;i<ids.length;i++){"+
    		"if(selectIds.indexOf(ids[i].affairId)!=-1)ids[i].checked=true;}"+
    		"doPigeonhole('new',"+ApplicationCategoryEnum.edoc.key()+",'listDone','');\r\n"+
    		"var archiveId = document.getElementById('archiveId').value;\r\n"+
    		"if(archiveId)pigeonholeForEdoc();}";
	
		    WebUtil.saveJavascript(js);
        }else if(sbInfo.length()>0){//有流程未结束的
        	//TODO
        }else{//所有的都设有预归档目录，不需要选择。
        	String alertInfo = ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.pigdoc.alert.list.success",successCount);
        	WebUtil.saveAlert(alertInfo);
        }
        return super.refreshWindow("parent"); 
//        if(sbInfo.length() > 0 || accInfo.length()>0){
//        	String err1="";
//        	String err2="";
//        	if(sbInfo.length()>0)
//        	{
//        		String[] sbInfos=sbInfo.toString().split(",");
//        		for(String s:sbInfos){
//        			if(!"".equals(err2))
//        				err2+="\r\n";
//        			err2+=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.err.nofinished.pig",s);
//        		}
//        	}
//        	if(accInfo.length()>0)
//        	{
//        		String[] accInfos=accInfo.toString().split(",");
//        		for(String s:accInfos){
//        			if(!"".equals(err1))
//        				err1+="\r\n";
//        			err1+=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.err.noaccess.pig",s);
//        		}
//        	}        	
//        	WebUtil.saveAlert(Strings.joinDelNull("\r\n",err1,err2));
//        }    
        
        //return super.refreshWindow("parent");        
    }
    private void printEdocJS(PrintWriter out){
        out.println("<script type=\"text/javascript\" charset=\"UTF-8\" src=\"" + SystemEnvironment.getA8ContextPath() + "/apps_res/edoc/js/edoc.js\"></script>");
    }
	public void setEdocMarkHistoryManager(
			EdocMarkHistoryManager edocMarkHistoryManager) {
		this.edocMarkHistoryManager = edocMarkHistoryManager;
	}

	//	系统管理员主页面
    public ModelAndView sysMain(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView("edoc/sysMain");
    	return modelAndView;
    } 
    
    //	系统管理员主页面
    @CheckRoleAccess(roleTypes={RoleType.Administrator,RoleType.AccountEdocAdmin})
    public ModelAndView sysCompanyMain(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView("edoc/sysComanyMain");
    	boolean isGroupVer=false;
    	
    	isGroupVer=(Boolean)SysFlag.sys_isGroupVer.getFlag();
    	
    	modelAndView.addObject("isGroupVer",isGroupVer);
    	return modelAndView;
    }
    
    /**
     * 暂存待办
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView doZCDB(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
        long summaryId = Long.parseLong(request.getParameter("summary_id"));
        long affairId = Long.parseLong(request.getParameter("affair_id"));
        String processId = request.getParameter("processId");
        boolean isRelieveLock = true;
        
        EdocSummary summary = null;
        Affair affair = affairManager.getById(affairId);
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.insertPeople,
	        		response, ApplicationCategoryEnum.collaboration)){
	        	isRelieveLock = false;
	        	return null;
	        }
	
	        EdocOpinion opinion = new EdocOpinion();
	        bind(request, opinion);
	        opinion.setIdIfNew();
	        opinion.setIsHidden(request.getParameterValues("isHidden") != null);
	        String attitude = request.getParameter("attitude");
	        if(!Strings.isBlank(attitude)){
	        	opinion.setAttribute(Integer.valueOf(attitude).intValue());
	        }else{
	        	opinion.setAttribute(com.seeyon.v3x.edoc.util.Constants.EDOC_ATTITUDE_NULL);
	        }
	        String content = request.getParameter("contentOP");
	        opinion.setContent(content);
	        //String afterSign = request.getParameter("afterSign");
        	//affair.setIsTrack("track".equals(afterSign));
        	String[] afterSign = request.getParameterValues("afterSign");
  	        Set<String> options = new HashSet<String>();
  	        if(afterSign!=null){
	  	        for(String option : afterSign){
	  	        	options.add(option);
	  	        }
  	        }
  	        //允许处理后归档和跟踪被同时选中，但是他们都不能和删除按钮同时选中
  	        if(options.size()>1 && options.contains("delete")){
  	        	options.remove("delete");
  	        }
  	        boolean track =  options.contains("track");
  	        //跟踪
  	        String trackMembers = request.getParameter("trackMembers");
  	        String trackRange = request.getParameter("trackRange");
  	        //不跟踪 或者 全部跟踪的时候不向部门跟踪表中添加数据，所以将下面这个参数串设置为空。
  	        if(!track || "1".equals(trackRange)) trackMembers = "";
  	        setTrack(affairId, track, trackMembers);
  	        
  	        
	        long nodeId=-1;
	        if(request.getParameter("currentNodeId")!=null && !"".equals(request.getParameter("currentNodeId")))
	        {
	        	nodeId=Long.parseLong(request.getParameter("currentNodeId"));
	        }
	        opinion.setNodeId(nodeId);
	        
	        String spMemberId = request.getParameter("supervisorId");
	        String superviseDate = request.getParameter("awakeDate");
	        String supervisorNames = request.getParameter("supervisors");
	        String title = request.getParameter("superviseTitle");
	        
	        summary = edocManager.getEdocSummaryById(summaryId, true);
	        
	        //为了保存流程日志中修改附件的记录在处理提交之前，所以将保存附件的操作提前了。bug29527
	        //保存附件
	        String oldOpinionIdStr=request.getParameter("oldOpinionId");
	        if(!"".equals(oldOpinionIdStr))
	        {//删除原来意见,上传附件等
	        	Long oldOpinionId=Long.parseLong(oldOpinionIdStr);
	        	attachmentManager.deleteByReference(summaryId, oldOpinionId);
	        	edocManager.deleteEdocOpinion(oldOpinionId);
	        }
	        
	        //使用附件组件重构--dongyj
	        /*this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, opinion.getId(), request);
	        //保存正文的附件
	        //是否修改了正文附件
	        String isContentAttchmentChanged=request.getParameter("isContentAttchmentChanged");
	        if("1".equals(isContentAttchmentChanged)){
	        	this.edocManager.updateAttachment(summary,affair,user,request);
	        }*/
            AttachmentEditHelper editHelper = new AttachmentEditHelper(request);
            if(editHelper.hasEditAtt()){//是否修改附件
            	edocManager.saveUpdateAttInfo(editHelper.attSize(),summaryId,editHelper.parseProcessLog(Long.parseLong(processId), nodeId));
            }
        	this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, opinion.getId(), request);
	        //使用附件组件重构 end
        	
        	//推送消息    affairId,memberId#affairId,memberId#affairId,memberId
		    String pushMessageMembers = request.getParameter("pushMessageMemberIds");
		    setPushMessagePara2ThreadLocal(pushMessageMembers);
        	
		    //如果当前操作执行了转PDF的操作。
        	String isConvertPdf=request.getParameter("isConvertPdf");
        	if(Strings.isNotBlank(isConvertPdf)){
        		createPdfBodies(request, summary);
        	}
        	
	        if(null!=supervisorNames && !"".equals(supervisorNames) && null!=spMemberId && !"".equals(spMemberId) && null!=superviseDate && !"".equals(superviseDate)){
	        	this.edocManager.zcdb(affair, opinion, title, spMemberId, supervisorNames,superviseDate, summary, processId, user.getId()+"");
	        }else{
	        	this.edocManager.zcdb(summary, affair, opinion, processId, user.getId()+"");
	        	if ("true".equals(request.getParameter("isDeleteSupervisior"))) {
					this.edocSuperviseManager.deleteSuperviseDetailAndSupervisors(summary);
				}
	        }
	        String draftOpinionId = request.getParameter("draftOpinionId");
	        if(Strings.isNotBlank(draftOpinionId)){ //修改草稿
	        	edocManager.deleteEdocOpinion(Long.parseLong(draftOpinionId));
	        }
	        
	        updateIndexManager.update(summaryId,EdocUtil.getAppCategoryByEdocType(summary.getEdocType()).getKey());
	        
	        //暂存待办提醒时间设置--start
	        String zcdbTimeStr=request.getParameter("zcdbTime");
	        EdocZcdb edocZcdb=edocZcdbManager.getEdocZcdbByAffairId(affairId);
	        if(zcdbTimeStr!=null && !("".equals(zcdbTimeStr))){
	        	Date zcdbTime = Datetimes.parse(zcdbTimeStr, Datetimes.datetimeWithoutSecondStyle);
		        if(edocZcdb!=null){
		        	edocZcdbManager.updateEdocZcdbByAffairId(affairId, zcdbTime);
		        	
		        	//新增定时消息
		        	edocManager.deleteZcdbQuartz(affairId,zcdbTime);
		        	edocManager.createZcdbQuartz(affairId,zcdbTime);
		        }else{
		        	edocZcdb=new EdocZcdb();
		        	edocZcdb.setIdIfNew();
		        	edocZcdb.setAffairId(affairId);
		        	edocZcdb.setZcdbTime(new Timestamp(zcdbTime.getTime()));
		        	edocZcdbManager.saveEdocZcdb(edocZcdb);
		        	//新增定时消息
		        	edocManager.createZcdbQuartz(affairId,zcdbTime);
		        }
			
	        }else{//如果没设置，也要保存一条记录，因为查询在办列表需要连接此表
	        	if(edocZcdb!=null){
	        		edocZcdbManager.deleteEdocZcdb(edocZcdb.getId());
		        	edocZcdb=new EdocZcdb();
		        	edocZcdb.setIdIfNew();
		        	edocZcdb.setAffairId(affairId);
		        	edocZcdb.setZcdbTime(null);
		        	edocZcdbManager.saveEdocZcdb(edocZcdb);
	        	}else{
		        	edocZcdb=new EdocZcdb();
		        	edocZcdb.setIdIfNew();
		        	edocZcdb.setAffairId(affairId);
		        	edocZcdb.setZcdbTime(null);
		        	edocZcdbManager.saveEdocZcdb(edocZcdb);
	        	}
	        }
	       //暂存待办提醒时间设置--end

	        PrintWriter out = response.getWriter();
	        out.println("<script>");
	        out.println("parent.doEndSign_pending();");
	        out.println("</script>");
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        	  //解锁正文文单
        	try{
        		unLock(user.getId(),summary);
        	}catch(Exception e){
        		log.error(e);
        	}
        }
        return null;
    }
    private void setPushMessagePara2ThreadLocal(String pushMessageMembers){
    	//推送消息    affairId,memberId#affairId,memberId#affairId,memberId
    	    List<Long[]> pushList = new ArrayList<Long[]>();
    	    if(Strings.isNotBlank(pushMessageMembers)){
    	    	String[] pushs = pushMessageMembers.split("#");
    	    	for(String s :pushs){
    	    		String[] s1 = s.split(",");
    	    		pushList.add(new Long[]{Long.valueOf(s1[0]),Long.valueOf(s1[1])});
    	    	}
    	    }
    	    DateSharedWithWorkflowEngineThreadLocal.setPushMessageMembers(pushList);
    	}
    public ModelAndView superviseList(HttpServletRequest request,HttpServletResponse response)throws Exception{
    	
    	ModelAndView mav = new ModelAndView("edoc/supervise/supervise_list_main");
    	
    	return mav;
    }

	public void setEdocInnerMarkDefinitionManager(
			EdocInnerMarkDefinitionManager edocInnerMarkDefinitionManager) {
		this.edocInnerMarkDefinitionManager = edocInnerMarkDefinitionManager;
	}

	public EdocSummaryManager getEdocSummaryManager() {
		return edocSummaryManager;
	}

	public void setEdocSummaryManager(EdocSummaryManager edocSummaryManager) {
		this.edocSummaryManager = edocSummaryManager;
	}

	public void setEdocSuperviseManager(EdocSuperviseManager edocSuperviseManager) {
		this.edocSuperviseManager = edocSuperviseManager;
	}
	
	public ModelAndView showList4QuoteFrame(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
    	ModelAndView modelAndView = new ModelAndView("edoc/list4QuoteFrame");
    	String appType = request.getParameter("appType");
    	modelAndView.addObject("controller", "edocController.do");
    	modelAndView.addObject("appType", appType);
    	return modelAndView;
    }
	
    /**
     * 列出我的待办、已办、已发，并根据是否允许转发进行权限过滤，用在协同用引用场�?
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView list4Quote(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	ModelAndView modelAndView = new ModelAndView("edoc/list4Quote");
    	
        String condition = request.getParameter("condition");
        String textfield = request.getParameter("textfield");
        String textfield1 = request.getParameter("textfield1");
        
        ApplicationCategoryEnum appEnum = ApplicationCategoryEnum.edocSend;
        String coltype = request.getParameter("appType");
        if(Strings.isNotBlank(coltype)){
        	appEnum = ApplicationCategoryEnum.valueOf(Integer.parseInt(coltype));
        }
        
        List<EdocSummaryModel> queryList = this.edocManager.queryByCondition4Quote(appEnum, condition, textfield, textfield1);
        modelAndView.addObject("csList", queryList);
        
        Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
        Metadata deadline = metadataManager.getMetadata(MetadataNameEnum.collaboration_deadline); //处理期限 attitude
        colMetadata.put(MetadataNameEnum.collaboration_deadline.toString(), deadline);           
        modelAndView.addObject("colMetadata", colMetadata);
        
        Metadata comImportanceMetadata = metadataManager.getMetadata(MetadataNameEnum.common_importance);
        
        modelAndView.addObject("comImportanceMetadata", comImportanceMetadata);
        modelAndView.addObject("controller", "edocController.do");
        modelAndView.addObject("appType", coltype);
        
    	return modelAndView;
    }
    
    private void zcdbSupervise(HttpServletRequest request,HttpServletResponse response,EdocSummary edocSummary,boolean isNew,int state,boolean sendMessage) {
		String supervisorId = request.getParameter("supervisorId");
        String supervisors = request.getParameter("supervisors");
        String awakeDate = request.getParameter("awakeDate");
        if(supervisorId != null && !"".equals(supervisorId) && awakeDate != null && !"".equals(awakeDate)) {
        	User user = CurrentUser.get();
	        //boolean canModifyAwake = "on".equals(request.getParameter("canModifyAwake"))?true:false;
	        String superviseTitle = request.getParameter("superviseTitle");
	        Date date = Datetimes.parse(awakeDate, Datetimes.dateStyle);
	        String[] idsStr = supervisorId.split(",");
	        long[] ids = new long[idsStr.length];
	        int i = 0;
	        for(String id:idsStr) {
	        	ids[i] = Long.parseLong(id);
	        	i++;
	        }
	        if(isNew)
	        	this.colSuperviseManager.save(1, edocSummary.getSubject(),superviseTitle,user.getId(),user.getName(), supervisors, ids, date, Constant.superviseType.edoc.ordinal(), edocSummary.getId(),state,sendMessage, null);
	        else
	        	this.colSuperviseManager.update(1,edocSummary.getSubject(),superviseTitle,user.getId(),user.getName(), supervisors, ids, date, Constant.superviseType.edoc.ordinal(), edocSummary.getId(),state,sendMessage, null);
        }
	}
    
    private void saveColSupervise(HttpServletRequest request,HttpServletResponse response,EdocSummary edocSummary,boolean isNew,boolean sendMessage) throws Exception{
		String supervisorId = request.getParameter("supervisorId");
        String supervisors = request.getParameter("supervisors");
        String awakeDate = request.getParameter("awakeDate");
        if(supervisorId != null && !"".equals(supervisorId) && awakeDate != null && !"".equals(awakeDate)) {
        	User user = CurrentUser.get();
	        //boolean canModifyAwake = "on".equals(request.getParameter("canModifyAwake"))?true:false;
	        String title = request.getParameter("title");
	        if(Strings.isBlank(title)){
	        	title = request.getParameter("superviseTitle");
	        }
	        Date date = Datetimes.parse(awakeDate, Datetimes.dateStyle);
	        String[] idsStr = supervisorId.split(",");
	        long[] ids = new long[idsStr.length];
	        int i = 0;
	        for(String id:idsStr) {
	        	ids[i] = Long.parseLong(id);
	        	i++;
	        }
	        	edocSuperviseManager.superviseForTemplate("100", supervisorId, supervisors, awakeDate,edocSummary,title);
        }else if(supervisorId==null||"".equals(supervisorId)){//如果为空，删除督办。
        	if(edocSummary!=null&&edocSummary.getId()!=null){
        		edocSuperviseManager.deleteSuperviseDetailAndSupervisors(edocSummary);
        	}
        }
	}

	/**
	 * @param colSuperviseManager the colSuperviseManager to set
	 */
	public void setColSuperviseManager(ColSuperviseManager colSuperviseManager) {
		this.colSuperviseManager = colSuperviseManager;
	}
	
	
	//公文查询模块Controller
	
	public ModelAndView edocSearchMain(HttpServletRequest request,HttpServletResponse response)throws Exception{
		
		ModelAndView mav = new ModelAndView("edoc/docSearch/edocSearchMain");
		//ModelAndView mav = new ModelAndView("edoc/docSearch/searchWhere");
		Metadata edocTypeMetadata = metadataManager.getMetadata(MetadataNameEnum.edoc_doc_type);
        Metadata  sendTypeMetadata= metadataManager.getMetadata(MetadataNameEnum.edoc_send_type);
        Metadata PTypeMetadata=metadataManager.getMetadata(MetadataNameEnum.edoc_doc_party); 
        Metadata ATypeMetadata=metadataManager.getMetadata(MetadataNameEnum.edoc_doc_administrative);
        //lijl添加(屏闭注入的html脚本),GOV-2942.【公文管理-公文查询】页面按效果图修改。------------------Start
        if(edocTypeMetadata!=null){
        	List<MetadataItem> etm=edocTypeMetadata.getItems();
        	for(MetadataItem me:etm){
        		me.setLabel(Functions.toHTML(me.getLabel()));
        	}
        }
        if(sendTypeMetadata!=null){
        	List<MetadataItem> stm=sendTypeMetadata.getItems();
        	for(MetadataItem meta:stm){
        		meta.setLabel(Functions.toHTML(meta.getLabel()));
        	}
        }
        if(PTypeMetadata!=null){
        	List<MetadataItem> mdi=PTypeMetadata.getItems();
        	for(MetadataItem mi:mdi){
        		mi.setLabel(Functions.toHTML(mi.getLabel()));
        	}
        }
        if(ATypeMetadata!=null){
        	List<MetadataItem> atm=ATypeMetadata.getItems();
        	for(MetadataItem mi1:atm){
        		mi1.setLabel(Functions.toHTML(mi1.getLabel()));
        	}
        }
        //lijl添加(屏闭注入的html脚本),GOV-2942.【公文管理-公文查询】页面按效果图修改。------------------End
        mav.addObject("PTypeMetadata",PTypeMetadata);
        mav.addObject("ATypeMetadata",ATypeMetadata);
        mav.addObject("edocTypeMetadata", edocTypeMetadata);
        mav.addObject("sendTypeMetadata", sendTypeMetadata);		
		return mav;
	}
	
	public ModelAndView edocSearchEntry(HttpServletRequest request,
			HttpServletResponse response) throws Exception {	
		ModelAndView mav = new ModelAndView("edoc/docSearch/edocQueryIndex");		
		return mav;
	}
	
	public ModelAndView edocSearchWhere(HttpServletRequest request,
			HttpServletResponse response) throws Exception {	
		ModelAndView mav = new ModelAndView("edoc/docSearch/searchWhere");
		Metadata edocTypeMetadata = metadataManager.getMetadata(MetadataNameEnum.edoc_doc_type);
        Metadata  sendTypeMetadata= metadataManager.getMetadata(MetadataNameEnum.edoc_send_type);
        mav.addObject("edocTypeMetadata", edocTypeMetadata);
        mav.addObject("sendTypeMetadata", sendTypeMetadata);
		return mav;
	}
	
	public ModelAndView listEdocSearchReult(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		Locale local = LocaleContext.getLocale(request);
		String resource = "com.seeyon.v3x.common.resources.i18n.SeeyonCommonResources";
		final String commonTrue = ResourceBundleUtil.getString(resource, local, "common.true"); 
		final String commonFalse = ResourceBundleUtil.getString(resource, local, "common.false"); 
		
		ModelAndView mav = new ModelAndView("edoc/docSearch/searchResult");
		long curUserId= CurrentUser.get().getId();
		EdocSearchModel em=new EdocSearchModel();
		bind(request, em);
			
		final List<EdocSummaryModel> result=edocManager.queryByCondition(curUserId, em,true); 
		
		//自定义查询-start
        List<QueryCol> queryColList = new ArrayList<QueryCol>();
 
		
		String colId = request.getParameter("displayCol");  
		if(colId != null && !colId.equals("")){
			QueryColTemplate template = new QueryColTemplate();
			List list = null;
			if(em.getEdocType() == 0){
				list = template.getQueryCol(colId, new PackageColValueInter(){
					public void packageValue(String label,List<Object> values){
						for(EdocSummaryModel model : result){
							
							if(label.equals(EdocQueryColConstants.SEND_SECRETLEVEL)){
								values.add(model.getSummary().getSecretLevel());
							}
							else if(label.equals(EdocQueryColConstants.SEND_SUBJECT)){
								values.add(model.getSummary().getSubject());
							}
							else if(label.equals(EdocQueryColConstants.SEND_WORD)){
								values.add(model.getSummary().getDocMark());
							}
							else if(label.equals(EdocQueryColConstants.SEND_TO_UNIT)){
								values.add(model.getSummary().getSendTo());
							}
							else if(label.equals(EdocQueryColConstants.ISSUER)){
								values.add(model.getSummary().getIssuer());
							}
							else if(label.equals(EdocQueryColConstants.SEND_SENDINGDATE)){
								values.add(model.getSummary().getSigningDate());
							}
							else if(label.equals(EdocQueryColConstants.ISPIG)){
								if(model.getSummary().getHasArchive()){
									values.add(commonTrue);
								}else{
									values.add(commonFalse);
								}
							}
							else if(label.equals(EdocQueryColConstants.PIGE_PATH)){
								values.add(model.getArchiveName());
							}
							else if(label.equals(EdocQueryColConstants.SEND_COPIES)){
								values.add(model.getSummary().getCopies());
							}
							
						}
					}
				});
			}
			else if(em.getEdocType() == 1){
				list = template.getQueryCol(colId, new PackageColValueInter(){
					public void packageValue(String label,List<Object> values){
						for(EdocSummaryModel model : result){
							
							if(label.equals(EdocQueryColConstants.SEND_SECRETLEVEL)){
								values.add(model.getSummary().getSecretLevel());
							}
							else if(label.equals(EdocQueryColConstants.SEND_SUBJECT)){
								values.add(model.getSummary().getSubject());
							}
							else if(label.equals(EdocQueryColConstants.SEND_WORD)){
								values.add(model.getSummary().getDocMark());
							}
							else if(label.equals(EdocQueryColConstants.REC_FROMUNIT)){
								values.add(model.getSummary().getSendUnit());
							}
							else if(label.equals(EdocQueryColConstants.REG_PERSON)){
								values.add(model.getSummary().getCreatePerson());
							}
							else if(label.equals(EdocQueryColConstants.REG_DATE)){
								values.add(model.getSummary().getCreateTime());
							}
							else if(label.equals(EdocQueryColConstants.ISPIG)){
								if(model.getSummary().getHasArchive()){
									values.add(commonTrue);
								}else{
									values.add(commonFalse);
								}
							}
							else if(label.equals(EdocQueryColConstants.PIGE_PATH)){
								values.add(model.getArchiveName());
							}
							else if(label.equals(EdocQueryColConstants.SEND_COPIES)){
								values.add(model.getSummary().getCopies());
							}
						}
					}
				});
			}
			else if(em.getEdocType() == 2){
				list = template.getQueryCol(colId, new PackageColValueInter(){
					public void packageValue(String label,List<Object> values){
						for(EdocSummaryModel model : result){
							
							if(label.equals(EdocQueryColConstants.SEND_SECRETLEVEL)){
								values.add(model.getSummary().getSecretLevel());
							}
							else if(label.equals(EdocQueryColConstants.SEND_SUBJECT)){
								values.add(model.getSummary().getSubject());
							}
							else if(label.equals(EdocQueryColConstants.SEND_WORD)){
								values.add(model.getSummary().getDocMark());
							}
							else if(label.equals(EdocQueryColConstants.SEND_TO_UNIT)){
								values.add(model.getSummary().getSendTo());
							}
							else if(label.equals(EdocQueryColConstants.SEND_CREATEPERSON)){
								values.add(model.getSummary().getCreatePerson());
							}
							else if(label.equals(EdocQueryColConstants.CREATE_DATE)){
								values.add(model.getSummary().getCreateTime());
							}
							
							else if(label.equals(EdocQueryColConstants.ISPIG)){
								if(model.getSummary().getHasArchive()){
									values.add(commonTrue);
								}else{
									values.add(commonFalse);
								}
							}
							else if(label.equals(EdocQueryColConstants.PIGE_PATH)){
								values.add(model.getArchiveName());
							}
							else if(label.equals(EdocQueryColConstants.SEND_COPIES)){
								values.add(model.getSummary().getCopies());
							}
						}
					}
				});
			}
			queryColList =list;

			mav.addObject("queryState", 1);
		}else{
			mav.addObject("queryState", 0);
		}
		mav.addObject("colId",colId);
		mav.addObject("queryColList",queryColList);
		//自定义查询-end

		mav.addObject("result",result);
		mav.addObject("controller", "edocController.do");
		mav.addObject("edocType",em.getEdocType());
		
		Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
		mav.addObject("colMetadata", colMetadata);
		
		return mav;
	}
	  
	
	/**
     * 转到登记簿页面
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView sendRegister(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
//    	String edocType=request.getParameter("edocType");
//    	String url = "0".equals(edocType) ? "edoc/edocSendRegister" : "edoc/edocRecRegister";
    	ModelAndView modelAndView = new ModelAndView("edoc/edocSendRegister");
    	return modelAndView;     
    }
	
    
    //打开发文收文登记簿字段显示设置窗口
	public ModelAndView openEdocSetting(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		String edocType = request.getParameter("edocType");
		Map<Integer,String> leftMap = new LinkedHashMap<Integer,String>();
		
		if(edocType.equals("0")){
			leftMap.putAll(EdocQueryColConstants.sendEdocColMap);
		}else{
			leftMap.putAll(EdocQueryColConstants.recEdocColMap);
		}
		
		Map<Integer,String> targetMap = new LinkedHashMap<Integer,String>();
		String displayCol = request.getParameter("displayCol");
		if(displayCol != null && !displayCol.equals("")){
			String[] colIds = displayCol.split(",");
			for(int i=0;i<colIds.length;i++){
				String label = EdocQueryColConstants.queryColMap.get(Integer.parseInt(colIds[i]));
				targetMap.put(Integer.parseInt(colIds[i]),label);
				leftMap.remove(Integer.parseInt(colIds[i]));
			}
		} 
		ModelAndView mav = new ModelAndView("edoc/docSetting");
		mav.addObject("targetMap", targetMap); 
		mav.addObject("leftMap", leftMap); 
		return mav;
	}
	
	//打开自定义查询字段显示设置窗口
	public ModelAndView openSearchEdocSetting(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		String edocType = request.getParameter("edocType");
		Map<Integer,String> leftMap = new LinkedHashMap<Integer,String>();
		
		if(edocType.equals("0")){  //发文，签报
			leftMap.putAll(EdocQueryColConstants.sendSearchEdocColMap);
		}else if(edocType.equals("1")){ 
			leftMap.putAll(EdocQueryColConstants.recSearchEdocColMap);
		}else if(edocType.equals("2")){ 
			leftMap.putAll(EdocQueryColConstants.signSearchEdocColMap);
		}
		
		Map<Integer,String> targetMap = new LinkedHashMap<Integer,String>();
		String displayCol = request.getParameter("displayCol");
		if(displayCol != null && !displayCol.equals("")){
			String[] colIds = displayCol.split(",");
			for(int i=0;i<colIds.length;i++){
				String label = EdocQueryColConstants.queryColMap.get(Integer.parseInt(colIds[i]));
				targetMap.put(Integer.parseInt(colIds[i]),label);
				leftMap.remove(Integer.parseInt(colIds[i]));
			}
		} 
		ModelAndView mav = new ModelAndView("edoc/docSetting");
		mav.addObject("targetMap", targetMap); 
		mav.addObject("leftMap", leftMap); 
		return mav;
	}
	
	
	/**
	 * 发文登记簿查询
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView listSendEdocSearchReultByDocManager(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView("edoc/sendRegisterResult");
		EdocSearchModel em=new EdocSearchModel();
		bind(request, em);
		
		final List<EdocSummaryModel> result=edocManager.queryByDocManager(em,true,CurrentUser.get().getAccountId());
		List<QueryCol> queryColList = new ArrayList<QueryCol>();
 
		
		String colId = request.getParameter("displayCol");  
		if(colId != null && !colId.equals("")){
			QueryColTemplate template = new QueryColTemplate();
			queryColList = template.getQueryCol(colId, new PackageColValueInter(){
				public void packageValue(String label,List<Object> values){
					for(EdocSummaryModel model : result){
						if(label.equals(EdocQueryColConstants.SEND_WORD)){
							values.add(model.getSummary().getDocMark());
						}
						else if(label.equals(EdocQueryColConstants.SEND_SUBJECT)){
							values.add(model.getSummary().getSubject());
						}
						else if(label.equals(EdocQueryColConstants.SEND_SENDINGDATE)){
							values.add(model.getSummary().getSigningDate());
						}
						else if(label.equals(EdocQueryColConstants.SEND_CREATEPERSON)){
							values.add(model.getSummary().getCreatePerson());
						}
						else if(label.equals(EdocQueryColConstants.SEND_SECRETLEVEL)){
							values.add(model.getSummary().getSecretLevel());
						}
						else if(label.equals(EdocQueryColConstants.SEND_KEEPPERIOD)){
							values.add(model.getSummary().getKeepPeriod());
						}
						else if(label.equals(EdocQueryColConstants.SEND_URGENTLEVEL)){
							values.add(model.getSummary().getUrgentLevel());
						}
						else if(label.equals(EdocQueryColConstants.SEND_COPIES)){
							values.add(model.getSummary().getCopies());
						}
						else if(label.equals(EdocQueryColConstants.SEND_SENDUNIT)){
							values.add(model.getSummary().getSendUnit());
						}
						//分发人
						else if(label.equals(EdocQueryColConstants.SEND_DISTRIBUTER)){
							values.add(model.getSender());
						}
						
					}
				}
			});
			mav.addObject("queryState", 1);
		}else{
			mav.addObject("queryState", 0);
		}
		mav.addObject("colId",colId);
		mav.addObject("queryColList",queryColList);
		mav.addObject("result",result);
		mav.addObject("controller", "edocController.do");
		mav.addObject("edocType",em.getEdocType());
		
		Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
		mav.addObject("colMetadata", colMetadata);
		
		return mav;
	}
	
	
	
	/**
	 * 收文登记簿查询
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView listRecEdocSearchReultByDocManager(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
		
		
		ModelAndView mav = new ModelAndView("edoc/recRegisterResult");
		EdocSearchModel em=new EdocSearchModel();
		bind(request, em);
		em.setEdocType(1);
		
		final List<EdocSummaryModel> result=edocManager.queryByDocManager(em,true,CurrentUser.get().getAccountId());
		List<QueryCol> queryColList = new ArrayList<QueryCol>();
 
		String colId = request.getParameter("displayCol");  
		if(colId != null && !colId.equals("")){
			QueryColTemplate template = new QueryColTemplate();
			queryColList = template.getQueryCol(colId, new PackageColValueInter(){
				public void packageValue(String label,List<Object> values){
					for(EdocSummaryModel model : result){
						if(label.equals(EdocQueryColConstants.REC_SERIALNO)){
							values.add(model.getSummary().getSerialNo());
						}
						else if(label.equals(EdocQueryColConstants.REC_SUBJECT)){
							values.add(model.getSummary().getSubject());
						}
						else if(label.equals(EdocQueryColConstants.REC_SECRETLEVEL)){
							values.add(model.getSummary().getSecretLevel());
						}
						else if(label.equals(EdocQueryColConstants.REC_KEEPPERIOD)){
							values.add(model.getSummary().getKeepPeriod());
						}
						else if(label.equals(EdocQueryColConstants.REC_URGENTLEVEL)){
							values.add(model.getSummary().getUrgentLevel());
						}
						else if(label.equals(EdocQueryColConstants.REC_FROMUNIT)){
							values.add(model.getSummary().getSendUnit());
						}
						if(label.equals(EdocQueryColConstants.REC_DOCMARK)){
							values.add(model.getSummary().getDocMark());
						}
						else if(label.equals(EdocQueryColConstants.REC_COMMUNICATION_DATE)){
							values.add(model.getRecieveDate());
						}
						else if(label.equals(EdocQueryColConstants.REC_COPIES)){
							values.add(model.getSummary().getCopies());
						}
										
						else if(label.equals(EdocQueryColConstants.SEND_TO_UNIT)){
							values.add(model.getSummary().getSendTo());
						}
						else if(label.equals(EdocQueryColConstants.COPY_TO_UNIT)){
							values.add(model.getSummary().getCopyTo());
						}
						else if(label.equals(EdocQueryColConstants.ISSUER)){
							values.add(model.getSummary().getIssuer());
						}
						else if(label.equals(EdocQueryColConstants.C_PERSON)){
							values.add(model.getSigner());
						}
						else if(label.equals(EdocQueryColConstants.KEYWORD)){
							values.add(model.getSummary().getKeywords());
						}
						else if(label.equals(EdocQueryColConstants.REG_PERSON)){
							values.add(model.getRegisterUserName());
						}
						else if(label.equals(EdocQueryColConstants.REG_DATE)){
							values.add(model.getRegisterDate());
						}
						else if(label.equals(EdocQueryColConstants.SEND_DISTRIBUTER)){
							values.add(model.getDistributer());
						}
					}
				}
			});
			mav.addObject("queryState", 1);
		}else{
			mav.addObject("queryState", 0);
		}
		mav.addObject("colId",colId);
		mav.addObject("queryColList",queryColList);
		mav.addObject("result",result);
		mav.addObject("controller", "edocController.do");
		mav.addObject("edocType",em.getEdocType());
		
		Map<String, Metadata> colMetadata = metadataManager.getMetadataMap(ApplicationCategoryEnum.edoc);
		mav.addObject("colMetadata", colMetadata);
		
		return mav;
	}
	
	
	
	
	
	/**
	 * 导出公文查询结果到excel
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	 public ModelAndView exportQueryToExcel(HttpServletRequest request,HttpServletResponse response)throws Exception{
			
	    	// --  用于输出excel的标题 －－
	    	// --  start  --
			Locale local = LocaleContext.getLocale(request);
			String resource = "com.seeyon.v3x.edoc.resources.i18n.EdocResource";
			String stat_title = ResourceBundleUtil.getString(resource, local, "edoc.query.tables.label.GOV"); //标题
			String edocType=request.getParameter("edocType");
			
			List<EdocSummaryModel> result = null;
			
			String exportType = request.getParameter("exportType");
			//将查询结果组装成页面显示要用的形式
			DataRecord dataRecord = null;
			if("edocQuery".equals(exportType)){ 
				EdocSearchModel em=new EdocSearchModel();
				//bind(request, em);
				edocType=request.getParameter("_oldEdocType");
				String subject=request.getParameter("_oldSubject");
				String keywords=request.getParameter("_oldKeywords");
				String docMark=request.getParameter("_oldDocMark");
				String serialNo=request.getParameter("_oldSerialNo");
				String docType=request.getParameter("_oldDocType");
				String sendType=request.getParameter("_oldSendType");
				String createPerson=request.getParameter("_oldCreatePerson");
				String createTimeB=request.getParameter("_oldCreateTimeB");
				String createTimeE=request.getParameter("_oldCreateTimeE");
				String sendTo=request.getParameter("_oldSendTo");
				String sendToId=request.getParameter("_oldSendToId");
				String sendUnit=request.getParameter("_oldSendUnit");
				String issuer=request.getParameter("_oldIssuer");
				String signingDateA=request.getParameter("_oldSigningDateA");
				String show=request.getParameter("show");

				if(edocType!=null && !"".equals(edocType))
					em.setEdocType(Integer.parseInt(edocType));
				em.setSubject(subject);
				em.setKeywords(keywords);
				em.setDocMark(docMark);
				em.setSerialNo(serialNo);
				em.setDocType(docType);
				em.setSendType(sendType);
				em.setCreatePerson(createPerson);
				if(createTimeB!=null && !"".equals(createTimeB))
					em.setCreateTimeB(Datetimes.parseDate(createTimeB));
				if(createTimeE!=null && !"".equals(createTimeE))
					em.setCreateTimeE(Datetimes.parseDate(createTimeE));
				em.setSendTo(sendTo);
				em.setSendToId(sendToId);
				em.setSendUnit(sendUnit);
				em.setIssuer(issuer); 
				if(signingDateA!=null && !"".equals(signingDateA))
					em.setSigningDateA(Datetimes.parseDate(signingDateA));
				
				result = edocManager.queryByCondition(CurrentUser.get().getId(), em,false);
				dataRecord = EdocHelper.exportQueryToWebModel(request, this.response(result),stat_title,Integer.parseInt(edocType));
			}else{
				
				EdocSearchModel em=new EdocSearchModel();
//				bind(request, em);
				
				
				if(edocType!=null && !"".equals(edocType)) 
					em.setEdocType(Integer.parseInt(edocType));
				String signingDateA = request.getParameter("signingDateA");
				String signingDateB = request.getParameter("signingDateB");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if(signingDateA != null && !signingDateA.equals("")){
					em.setSigningDateA(sdf.parse(signingDateA)); 
				}
				if(signingDateB != null && !signingDateB.equals("")){
					em.setSigningDateB(sdf.parse(signingDateB));
				}
				String registerDateA = request.getParameter("registerDateB");
				String registerDateB = request.getParameter("registerDateE");
				if(registerDateA != null && !registerDateA.equals("")){
					em.setRegisterDateB(sdf.parse(registerDateA));
				}
				if(registerDateB != null && !registerDateB.equals("")){
					em.setRegisterDateE(sdf.parse(registerDateB));
				}
				
				result = edocManager.queryByDocManager(em,false,CurrentUser.get().getAccountId());
				dataRecord = EdocHelper.exportQueryToWebModel2(request, this.response(result),stat_title);
			}
	    	
			OrganizationHelper.exportToExcel(request, response, fileToExcelManager, stat_title, dataRecord);
	    	
	    	return null;
	 }
	 /**
	  * 进行封装的方法，封装成发送到页面的数据
	  * @param list
	  * @return
	  */
    private List<EdocSummaryModel> response(List<EdocSummaryModel> list) throws Exception{
    	if(list!=null&&list.size()!=0){
    		Metadata  secretLeveleMetadata = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);//得到公文密级的枚举
    		String secretLevel="";
    		for(EdocSummaryModel summary:list){
    			if(summary.getSummary().getSecretLevel()!=null){
        			secretLevel = this.getLabel(summary.getSummary().getSecretLevel(), secretLeveleMetadata) ;
        		}else{
        			secretLevel = this.getLabel(null, secretLeveleMetadata) ;
        		}
    			summary.getSummary().setSecretLevel(secretLevel);
    		}
    	}
    	return list;
    }
    private String getLabel(String itemValue,Metadata metadata){
		MetadataItem itms = metadata.getItem(itemValue);
		
		if (itms==null) return null;
		String label = null;
		if(itemValue != null) {
			
			if(Strings.isNotBlank(metadata.getResourceBundle())){ //在原数据中定义了resourceBundle
				label = ResourceBundleUtil.getString(metadata.getResourceBundle(), itms.getLabel());
			}
			
			if(label == null){
				return itms.getLabel();
			}			
		}

		
		return label;
	}
    /**
     * 公文处理中预发布公告,新闻
     * 
     * @author jincm 2008-5-29
     * @param request
     * @param response
     * @return 
     * @throws Exception
     */
    public ModelAndView preIssueNewsOrBull(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	ModelAndView mav = new ModelAndView("collaboration/preIssueNewsOrBull");
    	User user = CurrentUser.get();
    	
    	List typeList = new ArrayList();
    	String policyName = request.getParameter("policyName");
    	if(policyName.equals("newsaudit")){
    		typeList = newsTypeManager.getTypesCanNew(user.getId(), null, user.getAccountId());
    	}else {
    		typeList = bulTypeManager.getTypesCanNew(user.getId(), null, user.getAccountId());
    		//添加可以发集团的公告(上面一行代码已经获取了全部可以发起公告的板块，spaceType为null时表明不区分空间，无需另外添加集团公告板块)
    		//typeList.addAll(bulTypeManager.getTypesCanNew(user.getId(), BulTypeSpaceType.group, user.getAccountId()));
    	}
    	
    	if(typeList == null || typeList.size() == 0){
    		PrintWriter out = response.getWriter();
    		String msg = Constant.getString4CurrentUser("not.purview");
    		out.println("<script>");
			out.println("var arr = new Array();");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = arr;");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("</script>");
        	out.close();
        	return null;
    	}
    	mav.addObject("notHasOutworker", 1);
    	mav.addObject("type", policyName);
    	mav.addObject("typeList", typeList);
    	mav.addObject("typeObj", typeList.get(0));
    	return mav;
    }
    /**
     * Ajax判断是否有发布公告、新闻的权限
     * @param policyName  
     * @return true(有权限) false无权限
     * @throws Exception
     */
    
    public boolean AjaxjudgeHasPermitIssueNewsOrBull(String policyName)throws Exception{
    	User user = CurrentUser.get();
    	List typeList = new ArrayList();
    	if("newsaudit".equals(policyName)){
    		typeList = newsTypeManager.getTypesCanNew(user.getId(), null, user.getAccountId());
    	}else {
    		typeList = bulTypeManager.getTypesCanNew(user.getId(), null, user.getAccountId());
    	}
    	if(typeList==null||typeList.size()==0){
    		return false;//没有权限
    	}
    	return true;
    }
    /**
     * 发布公告
     * 
     * @author jincm 2008-5-29
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView issusBulletion(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	String errMsg="";

    	try{    	
    	User user = CurrentUser.get();
    	String typeId = request.getParameter("typeId");
    	String summaryId = request.getParameter("summaryId");
    	String memberIdsStr = request.getParameter("memberIdsStr");
    	
    	EdocSummary summary = edocManager.getEdocSummaryById(Long.parseLong(summaryId), true);
    	BulType type = this.bulTypeManager.getById(Long.parseLong(typeId));
    	BulData bean = new BulData();
    	bean.setIdIfNew();
    	
    	EdocBody body = summary.getFirstBody();
				
		bean.setTitle(summary.getSubject());//标题
    	bean.setContent(body.getContent()==null?"":body.getContent());//正文
    	bean.setCreateDate(new Timestamp(System.currentTimeMillis()));
    	bean.setPublishDate(new Timestamp(System.currentTimeMillis()));
		bean.setCreateUser(user.getId());
		//bean.setDataFormat(com.seeyon.v3x.common.constants.Constants.EDITOR_TYPE_HTML);
		bean.setReadCount(0);
		bean.setTypeId(Long.parseLong(typeId));
		bean.setType(type);
		bean.setTopOrder(Byte.valueOf("0"));
		bean.setPublishUserId(user.getId());
		bean.setAccountId(user.getAccountId());
		bean.setDeletedFlag(false);
//		是否允许打印，如果允许打印，转发的公告Office正文才允许保存、打印
		bean.setExt2(request.getParameter("allowPrint")); 
		//增加标识，表明此公告是由公文转发
		bean.setExt4(ApplicationCategoryEnum.edoc.name());
		
		bean.setDataFormat(body.getContentType());
		if(!com.seeyon.v3x.common.constants.Constants.EDITOR_TYPE_HTML.equals(body.getContentType()))
		{
			//复制office对应的正文
			V3XFile f=fileManager.clone(Long.parseLong(body.getContent()),true);
			bean.setContent(f.getId().toString());
			//复制正文对应的印章
			SignetManager sm=(SignetManager)ApplicationContextHolder.getBean("signetManager");
			sm.insertSignet(Long.parseLong(body.getContent()), f.getId());
			bean.setContentName(body.getContent());
			bean.setExt5(request.getParameter("ext5"));
		}
		//bean.
		
		Long _summaryId = Long.parseLong(summaryId);
		Long beanId = bean.getId();
		boolean hasAttFlag = this.attachmentManager.hasAttachments(_summaryId, _summaryId);
		if(hasAttFlag){
			this.attachmentManager.copy(_summaryId, _summaryId, beanId, beanId, ApplicationCategoryEnum.bulletin.key());//附件
			bean.setAttachmentsFlag(true);
		}
		if(type.getSpaceType().intValue() == com.seeyon.v3x.bulletin.util.Constants.BulTypeSpaceType.department.ordinal()){
			bean.setPublishScope("Department|"+type.getId().toString());
		}else{
			bean.setPublishScope(memberIdsStr);
		}
		
		//设置发布部门
		if(bean.getPublishDepartmentId()==null){
			//设置为发起者所在部门
			Long userId = bean.getCreateUser();
			Long depId=((BaseBulletinManager)this.bulDataManager).getBulletinUtils().getMemberById(userId).getOrgDepartmentId();
			bean.setPublishDepartmentId(depId);
		}
		//发布公告
		this.bulDataManager.saveCollBulletion(bean);
    	
		V3xOrgMember member = orgManager.getMemberById(bean.getPublishUserId());
		//直接发送不审合消息
		Set<Long> bulAudits = new HashSet<Long>();
		Set<V3xOrgMember> membersSet = orgManager.getMembersByTypeAndIds(bean.getPublishScope());
		if(membersSet != null && membersSet.size() > 0){
			for(V3xOrgMember om : membersSet){
				bulAudits.add(om.getId());
			}
		}
		/**
		operationlogManager.insertOplog(summary.getId(), ApplicationCategoryEnum.collaboration, 
        		Constant.OperationLogActionType.finishItem.name(), "col.operationlog.issusBulletion", user.getName(), new java.util.Date(), summary.getSubject());
		**/
		this.processLogManager.insertLog(user, Long.valueOf(summary.getProcessId()), 1l, ProcessLogAction.processEdoc, String.valueOf(ProcessLogAction.ProcessEdocAction.forwardBulletin.getKey())) ;
		userMessageManager.sendSystemMessage(
				MessageContent.get("bul.auditing",
				bean.getTitle(),member.getName()), 
				ApplicationCategoryEnum.bulletin,
				member.getId(), 
				MessageReceiver.get(bean.getId(),bulAudits,"message.link.bul.alreadyauditing",String.valueOf(bean.getId())),
				bean.getTypeId());	
    	}catch(Exception e)
    	{
    		log.error(e);
    		errMsg=Strings.escapeJavascript(e.getMessage());
    	} 
    	PrintWriter out = response.getWriter();
    	out.println("<script>");
		if(null!=errMsg&&errMsg.equals(""))
		{
			out.println("parent.SendBulltinResult(\""+"公告发布成功"+"\");"); 
		}
		else
		{
			out.println("parent.SendBulltinResult(\""+errMsg+"\");"); 
		}
		out.println("</script>");
		
    	return null;
    }
	/**
	 * Ajax判断文号定义是否被删除，并且判断内部文号是否已经存在（除开公文自己本身占用的文号）
	 * @param definitionId    下拉选择传进来的是文号定义ID，断号选择传进来的是edoc_mark表的ID
	 * @param serialNo		  内部文号
	 * @return  deleted（0：已删除  1：未删除）  exsit(0:不存在  1：存在)
	 */
	public String checkEdocMark(Long definitionId,String serialNo,Integer selectMode,String summaryId){
		int deleted=1;
		int exsit=0;
		//手动输入的时候不判断文号定义。
		if(definitionId!=null && definitionId.longValue()!=0){
			Long id=0L;
			if(selectMode==2){//断号选择
				EdocMark edocMark=edocMarkManager.getEdocMark(definitionId);
				if(edocMark!=null){
					EdocMarkDefinition definition=edocMark.getEdocMarkDefinition();
					if(definition!=null){
						id=definition.getId();
					}
				}
			}else{
				id=definitionId;
			}
			//判断文号定义是否已经删除
			 deleted=edocMarkDefinitionManager.judgeEdocDefinitionExsit(id);
		}
		 //判断内部文号是否已经存在
		if(serialNo!=null &&!"".equals(serialNo)){
			User user = CurrentUser.get();
			exsit=edocSummaryManager.checkSerialNoExsit(summaryId,serialNo,user.getLoginAccount());  
		}
		 
		return deleted+","+exsit;
	}
	/**
	 * 判断当前公文文号是否已经被占用（除开公文自己本身占用的文号）
	 * @param edocSummaryId  :公文ID
	 * @param serialNo		 :内部文号
	 * @return 0:不存在，1:已存在
	 */
	public String checkSerialNoExcludeSelf(String edocSummaryId,String serialNo){
		User user=CurrentUser.get();
		int exsit=edocSummaryManager.checkSerialNoExsit(edocSummaryId,serialNo,user.getLoginAccount());
		return String.valueOf(exsit);
	}

	/**
	 * 拟文人Ajax更新附件，记录日志，发送消息
	 * @return
	 */
    public ModelAndView updateAttachment(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
   		User user = CurrentUser.get();
		String id = request.getParameter("edocSummaryId");
		String affairId=request.getParameter("affairId");
		Long _affairId=0L;
		EdocSummary edocSummary = new EdocSummary();
		Affair affair=new Affair();
		String ret="SUCCESS";
		if (id != null && !"".equals(id)) {
			edocSummary = edocSummaryManager.findById(Long.parseLong(id));
		}
		if(affairId!=null && !"".equals(affairId)){
			affair= affairManager.getById(Long.parseLong(affairId));
		}
			
		try{
			this.edocManager.updateAttachment(edocSummary,affair,user,request);
		} catch (Exception e) {
			log.error("修改正文附件异常", e);
			ret="";
		}
		response.getWriter().write(ret);
		return null;
    }
    
    
    /**
     * 暂存待办提醒窗口
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView openZcdbTime(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
       
       // String edocType=request.getParameter("edocType"); //公文类型，收文，发文，签报？

        ModelAndView modelAndView = new ModelAndView("edoc/zcdbTime");
        
        //modelAndView.addObject("edocType", edocType);
        //modelAndView.addObject("edocState", edocState);

        
        return modelAndView;
    }
    
    /**
     * 归档修改历史列表窗口
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView showArchiveModifyLog(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        ModelAndView modelAndView = new ModelAndView("edoc/showArchiveModifyLog");
        
        String summaryId=request.getParameter("summaryId");
        List<EdocArchiveModifyLog> list=edocArchiveModifyLogManager.getListBySummaryId(Long.parseLong(summaryId));
        modelAndView.addObject("logList", list);
        
        return modelAndView;
    }
    //lijl添加,GOV-3864.公文管理-发文管理-已办-已办结-已归档-查看公文修改历史，有多页数据时，点击"下一页"或"末页"提示"被迫下线，原因：与服务器失去连接"
    public ModelAndView showArchiveModifyLog_Iframe(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

    	ModelAndView modelAndView = new ModelAndView("edoc/showArchiveModifyLog_iframe");
    	
    	String summaryId=request.getParameter("summaryId");
    	List<EdocArchiveModifyLog> list=edocArchiveModifyLogManager.getListBySummaryId(Long.parseLong(summaryId));
    	modelAndView.addObject("logList", list);
    	modelAndView.addObject("summaryId", summaryId);
	
    	return modelAndView;
	}
    /**
     * 组合查询窗口
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView openCombQuery(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
       
        String edocType=request.getParameter("edocType"); //公文类型，收文，发文
        String edocState=request.getParameter("edocState"); //公文状态，1待发，2已发，3待办，4已办

        ModelAndView modelAndView = new ModelAndView("edoc/edocquery/query");
        
        modelAndView.addObject("edocType", edocType);
        modelAndView.addObject("edocState", edocState);

		Metadata edocTypeMetadata = metadataManager.getMetadata(MetadataNameEnum.edoc_doc_type);
        Metadata sendTypeMetadata= metadataManager.getMetadata(MetadataNameEnum.edoc_send_type);
        Metadata secretLevelMetadata = metadataManager.getMetadata(MetadataNameEnum.edoc_secret_level);
        Metadata urgentLevelMetadata = metadataManager.getMetadata(MetadataNameEnum.edoc_urgent_level);
        modelAndView.addObject("edocTypeMetadata", edocTypeMetadata);//公文种类
        modelAndView.addObject("sendTypeMetadata", sendTypeMetadata); //行文类型	
        modelAndView.addObject("secretLevelMetadata", secretLevelMetadata); //密级
        modelAndView.addObject("urgentLevelMetadata", urgentLevelMetadata); //紧急程度
        
        return modelAndView;
    }
    
	public BulDataManager getBulDataManager() {
		return bulDataManager;
	}

	public void setBulDataManager(BulDataManager bulDataManager) {
		this.bulDataManager = bulDataManager;
	}

	public NewsTypeManager getNewsTypeManager() {
		return newsTypeManager;
	}

	public void setNewsTypeManager(NewsTypeManager newsTypeManager) {
		this.newsTypeManager = newsTypeManager;
	}

	public BulTypeManager getBulTypeManager() {
		return bulTypeManager;
	}

	public void setBulTypeManager(BulTypeManager bulTypeManager) {
		this.bulTypeManager = bulTypeManager;
	}

	public NewsDataManager getNewsDataManager() {
		return newsDataManager;
	}

	public void setNewsDataManager(NewsDataManager newsDataManager) {
		this.newsDataManager = newsDataManager;
	}

	public FileManager getFileManager() {
		return fileManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}
	
	private String getOpinionName(String category , long accountId)throws Exception{
		List<FlowPerm> list = flowPermManager.getFlowPermsByCategory(category, accountId);
		String opinions = "";
		for(FlowPerm perm : list){
			opinions += perm.getName() + ",";
		}
		if(opinions.endsWith(",")){
			opinions = opinions.substring(0, opinions.lastIndexOf(","));
		}
		return opinions;
	}

    private  String unescapeHTMLToString(String str){
    	if(null==str||str.equals("")){
    		return "";
    	}
    	str = str.replace("&amp;","&");
    	str = str.replace("&lt;","<");
    	str = str.replace("&gt;",">");
    	str = str.replace("<br>","");
    	str = str.replace("&#039;","\'");
    	str = str.replace("&#034;","\"");
    	
    	return str;
    }
    /**
     * 得到公文的所属部门的ID
     * 在主单位下，取主部门为公文所属部门，由于系统无法识别他由主岗发文还是由副岗发文，鉴于概率低，就取主岗部门了。
	 * 在兼职单位下，取多个兼职部门中的一个（按排序号，兼职序号在前的哪个部门 ）为公文所属部门。
	 * @param  accoutId :公文所属单位
     * @return  公文所属部门ID
     */
    private Long getEdocOwnerDepartmentId(Long accoutId){
    	User user=CurrentUser.get();
    	long currentDeptId=user.getDepartmentId();
    	if(accoutId!=user.getAccountId()){
    		try {
				Map<Long, List<ConcurrentPost>> map=orgManager.getConcurentPostsByMemberId(accoutId, user.getId());
				long min=-1;
				
				for(Long deptId:map.keySet()){
					List<ConcurrentPost> list=map.get(deptId);
					for(ConcurrentPost concurrentPost:list){
						if(min==-1) min=concurrentPost.getNumber();
						if(concurrentPost.getNumber()<min){
							min=concurrentPost.getNumber();
							currentDeptId=deptId;
						}
					}
				}
    		} catch (BusinessException e) {
				log.error("公文所属部门判断异常:", e);
			}
    	}
    	return currentDeptId;
    }
	private String getName(String ids,String seperator) throws Exception{
		 String[] sids = ids.split("[,]");
		 String name = "";
		 for(String sid : sids){
			 String[] std =  sid.split("[|]");
			 Long acccountId = Long.valueOf(std[1]);
			 if("".equals(name)){
				 name = EdocRoleHelper.getAccountById(acccountId).getName();
			 }else{
				 name += seperator+EdocRoleHelper.getAccountById(acccountId).getName();
			 }
		 }
		 return name;
	}
	private String getI18nSeperator(HttpServletRequest request){
		String seperator = "、";
		try{
			Locale locale =Functions.getLocale(request);
			String	sep   = ResourceBundleUtil.getString("com.seeyon.v3x.common.resources.i18n.SeeyonCommonResources", locale,"common.separator.label");
			if(Strings.isNotBlank(sep)) seperator = sep;
		}catch(Exception e){
			e.printStackTrace();
			log.error(e);
		}
		return seperator;
	}
	/**
	 * 判读公文是否已经被发送
	 * 
	 * @param summaryId
	 * 
	 * @return
	 */
	private boolean isBeSended(Long summaryId) {
		// 处理方法，使用affair提供的objectid查询词objectid下是否有app=22 and state=4的已发送记录
		// 有，则返回true
		StringBuffer qryHql = new StringBuffer();
		List<Object> list = new ArrayList<Object>();
//		list.add(ApplicationCategoryEnum.exSend.key());
//		list.add(StateEnum.edoc_exchange_sent.key());
		list.add(summaryId);
	//	list.add(false);
		qryHql.append("from EdocSendDetail e,EdocSendRecord r where e.sendRecordId=r.id and e.status = 0 and r.edocId = ? ");
		int queryCount = affairManager.getAffairQueryCount(qryHql.toString(),
				list.toArray(),
						new Type[] { Hibernate.LONG});
		if (queryCount > 0) {
			return true;
		} else {
			return false;
		}
		
		
	}
    
    /**
     * 解锁，公文提交或者暂存待办的时候进行解锁,与Ajax解锁一起，构成两次解锁，避免解锁失败，节点无法修改的问题出现
     * @param userId
     * @param summaryId
     */
    private void unLock(Long userId,EdocSummary summary){
    	if(summary == null) return ;
    	String bodyType = summary.getFirstBody().getContentType();
    	long summaryId = summary.getId();
    	
    	if(Constants.EDITOR_TYPE_OFFICE_EXCEL.equals(bodyType)||
    			Constants.EDITOR_TYPE_OFFICE_WORD.equals(bodyType)||
    			Constants.EDITOR_TYPE_WPS_EXCEL.equals(bodyType)||
    			Constants.EDITOR_TYPE_WPS_WORD.equals(bodyType)){
	    	//1、解锁office正文
    		try{
    			String contentId = summary.getFirstBody().getContent();
    		
	    		handWriteManager.deleteUpdateObj(contentId);
	    	}catch(Exception e){
	    		log.error("解锁office正文失败 userId:"+userId+" summaryId:"+summary.getId(),e);
	    	}
    	}else{
	    	//2、解锁html正文
	    	try{
	    		handWriteManager.deleteUpdateObj(String.valueOf(summaryId));
	    	}catch(Exception e){
	    		log.error("解锁html正文失败 userId:"+userId+" summaryId:"+summaryId ,e);
	    	}
    	}
    	//3、解锁公文单
    	try{
    		edocSummaryManager.deleteUpdateObj(String.valueOf(summaryId), String.valueOf(userId));
    	}catch(Exception e){
    		log.error("解锁公文单失败 userId:"+userId+" summaryId:"+summaryId,e);
    	}
    }
  
    /**
     * lijl添加2011-10-17 分发点击列表数据,显示详细信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView edocRegisterInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
        	ModelAndView modelAndView = new ModelAndView("edoc/edocRegister");
        	long registerId = request.getParameter("registerId")==null? -1L : Long.parseLong(request.getParameter("registerId"));
        	EdocRegister edocRegister = edocRegisterManager.getEdocRegister(registerId);
        	if(edocRegister==null) {
        	}
        	RegisterBody registerBody = edocRegister.getRegisterBody();
        	modelAndView.addObject("edocType", edocRegister.getEdocType());
        	modelAndView.addObject("controller", "edocController.do");
        	//是否允许拟文人修改附件。
        	boolean allowUpdateAttachment = EdocSwitchHelper.allowUpdateAttachment();
            modelAndView.addObject("allowUpdateAttachment", allowUpdateAttachment);            
            modelAndView.addObject("firstPDFId", registerBody!=null ? registerBody.getContent() : "");
            //只查找正文的附件。
            modelAndView.addObject("attachments", attachmentManager.getByReference(registerId, registerId));  
        	modelAndView.addObject("bean", edocRegister);
        	modelAndView.addObject("registerBody", registerBody);
        	modelAndView.addObject("curUser", CurrentUser.get());
        	return modelAndView;
        } catch (Exception e) {
        	log.error("",e);
        	PrintWriter out = response.getWriter();    	
        	out.println("<script>");
        	//out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(e.getMessage()) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"true\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("");
        	out.println("</script>");
        	return null;
		}
    }
	public ProcessLogManager getProcessLogManager() {
		return processLogManager;
	}

	public void setProcessLogManager(ProcessLogManager processLogManager) {
		this.processLogManager = processLogManager;
	}

	public void setDocHierarchyManager(DocHierarchyManager docHierarchyManager) {
		this.docHierarchyManager = docHierarchyManager;
	}


	public EdocMarkDefinitionManager getEdocMarkDefinitionManager() {
		return edocMarkDefinitionManager;
	}

	public void setEdocMarkDefinitionManager(
			EdocMarkDefinitionManager edocMarkDefinitionManager) {
		this.edocMarkDefinitionManager = edocMarkDefinitionManager;
	}

	public FileToExcelManager getFileToExcelManager() {
		return fileToExcelManager;
	}

	public void setFileToExcelManager(FileToExcelManager fileToExcelManager) {
		this.fileToExcelManager = fileToExcelManager;
	}
	
	/**
     * Portal事件来源指定分类
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @author lilong 2012-01-17
     */
    public ModelAndView showPortalCatagory(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	ModelAndView mav = new ModelAndView("collaboration/showPortalCatagory4Edoc");
    	return mav;
    }
    /**
     * portal显示重要程度的页面
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView showPortalImportLevel(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	ModelAndView mav = new ModelAndView("collaboration/showPortalImportLevel4Edoc");
    	return mav;
    }
	
	public ModelAndView sendBackToDraft(HttpServletRequest request,HttpServletResponse response) throws Exception{
		User user = CurrentUser.get();
        String _summaryId = request.getParameter("summary_id");
        String _affairId = request.getParameter("affairId");
        Long summaryId = Long.parseLong(_summaryId);
        Long affairId = Long.parseLong(_affairId);
        String processId = request.getParameter("processId");
        boolean isRelieveLock = true;
        EdocSummary summary = null ;
        Affair _affair = affairManager.getById(affairId);
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.stepback,
	        		response, ApplicationCategoryEnum.edoc)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        
	        PrintWriter out = response.getWriter();
	        String errMsg="";
	        if(_affair.getState() != StateEnum.col_pending.key()){
	        	errMsg=ColHelper.getErrorMsgByAffair(_affair);				
	        }
	        summary=edocSummaryManager.findById(summaryId);
	        if("".equals(errMsg))
	        {
//	        	if(summary.getHasArchive())
//	        	{
//	        		errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.archive.notoperate");
//	        	}else 
	        	if(summary.getFinished()){
	        		errMsg=ResourceBundleUtil.getString("com.seeyon.v3x.edoc.resources.i18n.EdocResource","edoc.state.end.stepback.alert","《"+summary.getSubject()+"》");
	        	}
	        }
	        if(!"".equals(errMsg))
	        {
	        	out.println("<script>");
	        	out.println("<!--");
	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(errMsg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  parent.parent.location.reload(true);");
	        	out.println("}");
	        	out.println("//-->");
	        	out.println("</script>");
	        	out.close();
	        	return null;	        	
	        }
	
	        //保存回退时的意见,附件�?
	        EdocOpinion signOpinion = new EdocOpinion();
	        bind(request, signOpinion);

	        String content = request.getParameter("contentOP");
	        signOpinion.setContent(content);
	        
	        String attitude = request.getParameter("attitude");
	        if(!Strings.isBlank(attitude)){
	        	signOpinion.setAttribute(Integer.valueOf(attitude).intValue());
	        }else{
	        	signOpinion.setAttribute(com.seeyon.v3x.edoc.util.Constants.EDOC_ATTITUDE_NULL);
	        }
	        //回退的时候,选择归档,跟踪无效
	        //String afterSign = request.getParameter("afterSign");
	
	        signOpinion.isDeleteImmediate = false;//"delete".equals(afterSign);
	        signOpinion.affairIsTrack = false;//"track".equals(afterSign);
	
	        signOpinion.setIsHidden(request.getParameterValues("isHidden") != null);
	        signOpinion.setIdIfNew();
	        
	        long nodeId=-1;
	        if(request.getParameter("currentNodeId")!=null && !"".equals(request.getParameter("currentNodeId")))
	        {
	        	nodeId=Long.parseLong(request.getParameter("currentNodeId"));
	        }
	        signOpinion.setNodeId(nodeId);
	        
//	      	//设置代理人信息
	        if(user.getId()!= _affair.getMemberId())
	        {
	        	signOpinion.setProxyName(user.getName());
	        }
	        signOpinion.setCreateUserId(_affair.getMemberId());
	        
	        //保存附件
	        //先删除原有附件，修改bug15597
	        String oldOpinionIdStr=request.getParameter("oldOpinionId");
	        if(!"".equals(oldOpinionIdStr))
	        {
	        	this.attachmentManager.deleteByReference(summaryId, Long.parseLong(oldOpinionIdStr));
	        }
	        //this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, signOpinion.getId(), request);
	        //使用附件组件重构
            AttachmentEditHelper editHelper = new AttachmentEditHelper(request);
            if(editHelper.hasEditAtt()){//是否修改附件
            	edocManager.saveUpdateAttInfo(editHelper.attSize(),summaryId,editHelper.parseProcessLog(Long.parseLong(processId), nodeId));
            }
        	this.attachmentManager.create(ApplicationCategoryEnum.edoc, summaryId, signOpinion.getId(), request);
	
	        boolean ok = edocManager.sendBackToDraft(summary, _affair,signOpinion);       
	
	        //回退成功后，跳到待办列表�?
	        //return super.refreshWorkspace();
	        out.println("<script>");
	    	out.println("parent.closeWindow();");
	    	out.println("</script>");
	    	out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
	           
            try{
            	//解锁正文文单
            	unLock(user.getId(),summary);
            }catch(Exception e){
            	log.error(e);
            }

        }
		return super.refreshWorkspace();
	}
	
	public ModelAndView beforeDraftSendHandle(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String draftChoose = request.getParameter("draftChoose");
		String affairId = request.getParameter("affairId");
		boolean result = this.edocManager.beforeDraftSendHandle(Long.parseLong(affairId), draftChoose);
		if(result) {
			if("toContinue".equals(draftChoose))
				return super.refreshWorkspace();
			else if("redo".equals(draftChoose))
				return send(request,response);
		}
		return null;
	}

	
	
	/**
	 * 进入加签页面（综合原加签、当前会签、多级会签的加签）
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView preInsertPeople(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
    	ModelAndView mav = null; 
    	
    	if((Boolean)BrowserFlag.PageBreak.getFlag(request)){
    		mav = new ModelAndView("edoc/insertPeople");
    	}else{//ipad
    		mav = new ModelAndView("collaboration/insertPeopleIpad");
    	}
    	User user = CurrentUser.get();
    	
    	String _summaryId = request.getParameter("summaryId");
        String _affairId = request.getParameter("affairId");
        Long affairId = Long.parseLong(_affairId);
        Long summaryId = Long.parseLong(_summaryId);
        String appName = request.getParameter("appName");  //相当于edoctype，0发文，1收文，2签报。但是协同=collaboration
        String appTypeName = request.getParameter("appTypeName");  // 多级会签用，判断当前应用是发文、收文、签报，是字符串，从而取到该应用的节点权限。
        String isForm = request.getParameter("isForm");
        String processId = request.getParameter("processId");
        
        PrintWriter out = response.getWriter();
        Affair affair = affairManager.getById(affairId);
        if(affair == null || affair.getState() != StateEnum.col_pending.key()){
			String msg=ColHelper.getErrorMsgByAffair(affair);
			out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("</script>");
        	out.close();
        	return null;
        }

		List<String> desList = null;
		String nodeMetadataName = "";
		int flowPermType = 1;  //流程权限的类型 0:协同 .  1:公文（默认是公文）
		String bundleName = "com.seeyon.v3x.edoc.resources.i18n.EdocResource"; //指定国际化资源文件,默认为公文
		String defaultPolicyId = null;  //节点权限值
	    if("0".equalsIgnoreCase(appName)){
			nodeMetadataName=MetadataNameEnum.edoc_send_permission_policy.name();  // 发文节点权限策略
			defaultPolicyId = BPMSeeyonPolicy.EDOC_POLICY_SHENPI.getId();
		}else if("1".equalsIgnoreCase(appName)){
			nodeMetadataName=MetadataNameEnum.edoc_rec_permission_policy.name();
			defaultPolicyId = BPMSeeyonPolicy.EDOC_POLICY_YUEDU.getId();
		}else if("2".equalsIgnoreCase(appName)){
			nodeMetadataName=MetadataNameEnum.edoc_qianbao_permission_policy.name();
			defaultPolicyId = BPMSeeyonPolicy.EDOC_POLICY_SHENPI.getId();
		}	

		//获取对应应用类型的所有节点策略
		List <FlowPerm> nodePolicyList = null;		
//      权限策略改动，需要充分验证(Mazc 2009-4-13)
//      自定义的流程取发起者所在单位（协同的关联单位）的节点权限， 模板的取模板所在单位的节点权限   
        Long flowPermAccountId = user.getLoginAccount();
        //ColSummary summary = colManager.getColSummaryById(summaryId, false);
       // if("collaboration".equalsIgnoreCase(appName) && summary != null){
        //	flowPermAccountId = ColHelper.getFlowPermAccountId(flowPermAccountId, summary, templeteManager);
        //}
       // else {//公文，包括发文，收文，签报
		EdocSummary edocSummary = edocManager.getEdocSummaryById(summaryId, false);
		if(edocSummary != null) {
			if(edocSummary.getTempleteId() != null) {
				Templete templete = templeteManager.get(edocSummary.getTempleteId());
				if(templete != null){
					flowPermAccountId = templete.getOrgAccountId();
				}
			}else{
				if(edocSummary.getOrgAccountId() != null){
					flowPermAccountId = edocSummary.getOrgAccountId();
				}
			}	
		}
		//}
		nodePolicyList = flowPermManager.getFlowpermsByStatus(nodeMetadataName, FlowPerm.Node_isActive, false, flowPermType, flowPermAccountId);
		mav.addObject("nodePolicyList",nodePolicyList);
		if(!"true".equals(isForm)){
			for(FlowPerm flowPerm : nodePolicyList){
				if("formaudit".equals(flowPerm.getName())){
					nodePolicyList.remove(flowPerm);
					break;
				}
			}
		}
		//获取对应应用下的所有节点策略说明
		desList = new ArrayList<String>();
		for(FlowPerm fp : nodePolicyList)
		{
			desList.add(fp.getName()+"split"+StringEscapeUtils.escapeJavaScript(fp.getDescription()));
		}
		
		mav.addObject("bundleName", bundleName);
		mav.addObject("nodePolicyList", nodePolicyList);
		mav.addObject("desList", desList);
		mav.addObject("summaryId", summaryId);
		mav.addObject("affairId", affairId);
		mav.addObject("defaultPolicyId", defaultPolicyId);
		mav.addObject("appName", appName);
		mav.addObject("appTypeName", appTypeName);
		mav.addObject("processId", processId);
		mav.addObject("isFormReadonly", affair.isFormReadonly());
		
		//当前会签流程
        FlowPerm flowPerm = null ;
    	EdocSummary summary2 = edocManager.getEdocSummaryById(summaryId, true);
    	MetadataNameEnum edocTypeEnum=EdocUtil.getEdocMetadataNameEnum(summary2.getEdocType());
		Long senderId = summary2.getStartUserId();
        V3xOrgMember sender = orgManager.getMemberById(senderId);
        Long flowPermAccountId2  = EdocHelper.getFlowPermAccountId(summary2 ,sender.getOrgAccountId(),templeteManager);
        flowPerm=flowPermManager.getFlowPerm(edocTypeEnum.name(), "huiqian", flowPermAccountId2);
	
    	mav.addObject("nodePolicy", flowPerm) ;
    	mav.addObject("from","edoc");
    	
        return mav;
    	
    }
	
    //加签
    public ModelAndView insertPeople(HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
    	User user = CurrentUser.get();
    	String processMode = request.getParameter("processMode");
        String _summaryId = request.getParameter("summaryId");
        String _affairId = request.getParameter("affairId");
        Long summaryId = Long.parseLong(_summaryId);
        Long affairId = Long.parseLong(_affairId);
        String policyId = request.getParameter("policyId");
        String processId = request.getParameter("processId");
        String policyName = request.getParameter("policyName");
        //String appName = request.getParameter("appName");
        boolean isFormOperationReadonly = "1".equals(request.getParameter("formOperationPolicy"));
        
//      权限策略改动，需要充分验证(Mazc 2009-4-13)
        //自定义的流程取发起者所在单位（协同的关联单位）的节点权限， 模板的取模板所在单位的节点权限

        EdocSummary edocSummary = null;
        String fCategoryName = MetadataNameEnum.col_flow_perm_policy.name();
        Long templeteId = 0L;
        Long summaryAccountId = 0L;
        Long caseId = null;
        String summaryProcessId = "";   //TODO ： 这个变量是否可以去掉，直接取前台传过来的PROCESSid

    	edocSummary = edocManager.getEdocSummaryById(summaryId, false);	
    	if(edocSummary == null ) return null;
    	templeteId = edocSummary.getTempleteId();
    	summaryAccountId = edocSummary.getOrgAccountId();
    	fCategoryName = EdocHelper.getCategoryName(edocSummary.getEdocType());
    	caseId = edocSummary.getCaseId();
    	summaryProcessId = edocSummary.getProcessId();
        
        Long flowPermAccountId = ColHelper.getFlowPermAccountId(user.getLoginAccount(), templeteId,summaryAccountId, templeteManager);
        FlowPerm perm = flowPermManager.getFlowPerm(fCategoryName, policyId, flowPermAccountId);
        if(perm == null){
        	PrintWriter out = response.getWriter();
			String msg = Constant.getString4CurrentUser("nodePolicy.not.existence");
			out.println("<script>");
        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
        	out.println("if(window.dialogArguments){"); //弹出
        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
        	out.println("  window.close();");
        	out.println("}else{");
        	out.println("  parent.getA8Top().reFlesh();");
        	out.println("}");
        	out.println("</script>");
        	out.close();
        	return null;
        }else{
        	try {
        		flowPermManager.refFlowPerm(perm.getFlowPermId(), Long.parseLong(user.getLoginAccount()+""), 1);
			} catch (Exception e) {
				log.error("", e);
			}
        }
        
        boolean isRelieveLock = true;
        try{
	        //检查同步锁
	        if(!ColHelper.colOperationLock(summaryId, user.getId(), user.getName(), ColLock.COL_ACTION.insertPeople,
	        		response, ApplicationCategoryEnum.collaboration)){
	        	isRelieveLock = false;
	        	return null;
	        }
	        
	        PrintWriter out = response.getWriter();
	        Affair affair = affairManager.getById(affairId);
	        if(affair.getState() != StateEnum.col_pending.key()){
				String msg = ColHelper.getErrorMsgByAffair(affair);
				out.println("<script>");
	        	out.println("alert(\"" + StringEscapeUtils.escapeJavaScript(msg) + "\")");
	        	out.println("if(window.dialogArguments){"); //弹出
	        	out.println("  window.returnValue = \"" + DATA_NO_EXISTS + "\";");
	        	out.println("  window.close();");
	        	out.println("}else{");
	        	out.println("  parent.getA8Top().reFlesh();");
	        	out.println("}");
	        	out.println("</script>");
	        	out.close();
	        	return null;
	        }
	
	        //保存选人界面返回的信�xi息
	        FlowData flowData = FlowData.flowdataFromRequest();
	        String node_process_mode = "";
	        if(flowData.getSeeyonPolicy() != null ){
	        	node_process_mode = flowData.getSeeyonPolicy().getProcessMode() ;
	        }
	        
	        BPMSeeyonPolicy seeyonPolicy = new BPMSeeyonPolicy(policyId, policyName);
	        if(Strings.isNotBlank(node_process_mode))
	        		seeyonPolicy.setProcessMode(node_process_mode) ;
	        //FIXME 
	        if(isFormOperationReadonly){
	        	seeyonPolicy.setFR("1");
	        }
	        flowData.setSeeyonPolicy(seeyonPolicy);
	        int iFlowType = 0;
	        switch(Integer.parseInt(processMode)){
	            case 0 : iFlowType = FlowData.FLOWTYPE_SERIAL;
	            break;
	            case 1 : iFlowType = FlowData.FLOWTYPE_PARALLEL;
	            break;
	            case 2 : iFlowType = FlowData.FLOWTYPE_MULTIPLE;
	            break;
	            case 3 : iFlowType = FlowData.FLOWTYPE_COLASSIGN;
	            break;
	            case 4 : iFlowType = FlowData.FLOWTYPE_NEXTPARALLEL;
	            break;
	        }
	        flowData.setType(iFlowType);
	        if (flowData.getPeople().isEmpty()) {
	        	String info = Constant.getString4CurrentUser("please.select.one");
	        	out.println("<script>");
	        	out.print("alert(\"" + StringEscapeUtils.escapeJavaScript(info) + "\"); ");
	        	out.println("parent.parent.document.getElementById('b1').disabled = false;");
	        	out.println("parent.parent.document.getElementById('b2').disabled = false;");
	        	out.println("</script>");
	        	out.close();
	        	return null;
	        }
	        
	        //判断当前节点下一节点的节点类型
	        WorkItemManager wim = null;
	    	BPMProcess process = null;
	        try {
	        	process = ColHelper.getModifyingProcess(processId, user.getId()+"");
	        	if(process == null)
	        		process = BPMProcess.fromXML(ColHelper.getRunningProcessByCaseId(caseId).toXML());
	        	
	        	if(iFlowType == FlowData.FLOWTYPE_NEXTPARALLEL){
		    		wim = ColHelper.getWorkitemManager();
		    		WorkItem workitem = wim.getWorkItemInfo(user.getId() + "", affair.getSubObjectId());
		    		BPMActivity currentActivity = process.getActivityById(workitem.getActivityId());
		    		List downTransitions = currentActivity.getDownTransitions();
		    		BPMTransition nextTran = (BPMTransition) downTransitions.get(0);
		    		BPMAbstractNode childNode = nextTran.getTo();
		    		BPMAbstractNode.NodeType nodeType = childNode.getNodeType();
		    		if(nodeType == BPMAbstractNode.NodeType.end ||
							nodeType == BPMAbstractNode.NodeType.join){
		    			String info = Constant.getString4CurrentUser("nextNode.is.specialNode");
			        	out.println("<script>");
			        	out.print("alert(\"" + StringEscapeUtils.escapeJavaScript(info) + "\");\n ");
			        	//out.print("parent.enAbleButton();");
			        	out.println("parent.parent.document.getElementById('b1').disabled = false;");
			        	out.println("parent.parent.document.getElementById('b2').disabled = false;");
			        	out.println("</script>");
			        	out.close();
						return null;
		    		}
	        	}
	    	}catch(ColException e){
	    		log.error("", e);
	    	}
	       
	        String caseLogXML = null;
	        String caseProcessXML = null;
	        String caseWorkItemLogXML = null;
	
	        edocManager.insertPeople(edocSummary, affair, flowData, process, user.getId()+"","insertPeople");

            if (caseId != null) {
                caseLogXML = colManager.getCaseLogXML(caseId);
                caseProcessXML = colManager.getModifyingProcessXML(summaryProcessId);
                caseWorkItemLogXML = colManager.getCaseWorkItemLogXML(caseId);
            }
            else if (Strings.isNotBlank(summaryProcessId)) {
                caseProcessXML = colManager.getProcessXML(processId);
            }
	        
	        caseProcessXML = Strings.escapeJavascript(caseProcessXML);
	        caseLogXML = Strings.escapeJavascript(caseLogXML);
	        caseWorkItemLogXML = Strings.escapeJavascript(caseWorkItemLogXML);
	        String process_desc_by = FlowData.DESC_BY_XML;
	        out.println("<script>");
        	if((Boolean)BrowserFlag.PageBreak.getFlag(request)){
        		out.println("if(parent.window.dialogArguments) {");
        		out.println("parent.window.dialogArguments.caseProcessXML = \"" + caseProcessXML + "\";");
		        out.println("parent.window.dialogArguments.caseLogXML = \"" + caseLogXML + "\";");
		        out.println("parent.window.dialogArguments.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
		        out.println("parent.window.dialogArguments.document.getElementById('process_desc_by').value = \"" + process_desc_by + "\";");
		        out.println("parent.window.dialogArguments.document.getElementById('process_xml').value = \"" + caseProcessXML + "\";");
		        out.println("parent.window.dialogArguments.selectInsertPeopleOK();");
		        out.println("parent.window.close();");
		        out.println("}else{");
		        out.println("parent.parent.window.dialogArguments.caseProcessXML = \"" + caseProcessXML + "\";");
		        out.println("parent.parent.window.dialogArguments.caseLogXML = \"" + caseLogXML + "\";");
		        out.println("parent.parent.window.dialogArguments.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
		        out.println("parent.parent.window.dialogArguments.document.getElementById('process_desc_by').value = \"" + process_desc_by + "\";");
		        out.println("parent.parent.window.dialogArguments.document.getElementById('process_xml').value = \"" + caseProcessXML + "\";");
		        out.println("parent.parent.window.dialogArguments.selectInsertPeopleOK();");
		        out.println("parent.parent.window.close();");
		        out.println("}");
        	}else{//ipad 公文协同页面呢结构层级不一样
        		out.println("parent.parent.caseProcessXML = \"" + caseProcessXML + "\";");
		        out.println("parent.parent.caseLogXML = \"" + caseLogXML + "\";");
		        out.println("parent.parent.caseWorkItemLogXML = \"" + caseWorkItemLogXML + "\";");
		        out.println("parent.parent.document.getElementById('process_desc_by').value = \"" + process_desc_by + "\";");
		        out.println("parent.parent.document.getElementById('process_xml').value = \"" + caseProcessXML + "\";");
		        out.println("parent.parent.selectInsertPeopleOK();");
		        out.println("parent.parent.$('#insertPeopleWin').dialog('destroy');");
        		 
        	}
	        out.println("</script>");
	        out.close();
	        return null;
        }catch(Exception e){
        	log.error("", e);
        }finally{
        	if(isRelieveLock)
        		ColLock.getInstance().removeLock(summaryId);
        }
        return null;
    }
	
	
	/**
	 * puyc 关联收文
	 * 通过edocId和edocType查找，如果在EdocSummary有记录，则返回收文单
	 * 如果没有记录，则在EdocRegister 查找，如果有记录，则返回登记单 
	 * 如果没有记录，则在EdocRecieveRecord查找，如果有记录，则返回签收单
	 * 如果没有记录，则提示，资源不存在
	 */
	public String relationReceive(String relationEdocIdStr, String edocTypeStr) {
		Long relationEdocId = Strings.isNotBlank(relationEdocIdStr) ? Long
				.parseLong(relationEdocIdStr) : null;
		int relationEdocType = Strings.isNotBlank(edocTypeStr) ? Integer
				.parseInt(edocTypeStr) : -1;
		String relationUrl = "";//收文的路径
		if (relationEdocId != null && relationEdocType != -1) {
			EdocSummary edocSummary = this.edocSummaryRelationManager
					.findEdocSummary(relationEdocId, relationEdocType);
			if (edocSummary != null) {// 收文单
				relationUrl = "edocController.do?method=detail&summaryId="+ relationEdocId;
			} else {
				EdocRegister edocRegister = this.edocSummaryRelationManager
						.findEdocRegister(relationEdocId, relationEdocType);
				if (edocRegister != null) {// 登记单
					relationUrl = "edocController.do?method=edocRegisterDetail&registerId="
							+ edocRegister.getId();
				} else {
					EdocRecieveRecord edocRecieveRecord = this.edocSummaryRelationManager
							.findEdocRecieveRecord(relationEdocId);
					if (edocRecieveRecord != null) {//签收单
						relationUrl = "exchangeEdoc.do?method=edit&modelType=received&from=tobook&id="
								+ edocRecieveRecord.getId();
					}
				}
			}

		}
		return relationUrl;
	}

	/*
	 * 关联发文
	 */
	public ModelAndView relationNewEdoc(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = new ModelAndView("edoc/relationNewEdoc"); 
		String recEdocIdStr = request.getParameter("recEdocId");
		String recTypeStr = request.getParameter("recType");
		String forwardType = request.getParameter("forwardType");
		List<EdocSummary> newEdocList = new ArrayList<EdocSummary>();
		User user = CurrentUser.get();
		Long createUserId = user.getId();  
		if (Strings.isNotBlank(recEdocIdStr) && Strings.isNotBlank(recTypeStr)) { 
			if(Strings.isBlank(forwardType)){
				newEdocList = this.edocSummaryRelationManager.findNewEdoc(
						Long.parseLong(recEdocIdStr), createUserId,
						Integer.parseInt(recTypeStr));
			}
			else if("registered".equals(forwardType)){
				List<EdocSummary> newEdocList1 = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(
						Long.parseLong(recEdocIdStr), createUserId,
						Integer.parseInt(recTypeStr),1); 
				if(newEdocList1 != null){
        			newEdocList.addAll(newEdocList1);
        		}
				
				EdocRegister edocRegister = edocRegisterManager.getEdocRegister(Long.parseLong(recEdocIdStr));
				
				long recieveId = edocRegister.getRecieveId();
            	if(recieveId != -1){
            		List<EdocSummary> newEdocList2 = this.edocSummaryRelationManager.findNewEdoc(recieveId, user.getId(), 1);
            		if(newEdocList2 != null){
            			newEdocList.addAll(newEdocList2);
            		}
            	}
				
			}
			else if("waitSent".equals(forwardType)||  "listSent".equals(forwardType)){ 
//				newEdocList = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(
//						Long.parseLong(recEdocIdStr), createUserId,
//						Integer.parseInt(recTypeStr),2);
				
				//待分发
				
				List<EdocSummary> newEdocList1 = null;
				EdocRegister edocRegister = edocRegisterManager.findRegisterByDistributeEdocId(Long.parseLong(recEdocIdStr));
				if(edocRegister != null){
					newEdocList1 = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(
							edocRegister.getId(), createUserId,
							Integer.parseInt(recTypeStr),2); 
				}
				if(newEdocList1 != null){
					newEdocList.addAll(newEdocList1);
				}
				
				List<EdocSummary> newEdocList2 = this.edocSummaryRelationManager.findNewEdocByRegisteredOrWaitSent(
						Long.parseLong(recEdocIdStr), createUserId,
						Integer.parseInt(recTypeStr),2); 
				if(newEdocList2 != null){
					newEdocList.addAll(newEdocList2);
				}
			}
		}
		
		modelAndView.addObject("newEdocList", newEdocList);
		return modelAndView;
	}
	
	
	
}

